Django temple渲染

from django.template import Context, Template
t = Template('My name is {{ name }}.')
c = Context({'name': 'Stephane'})
t.render(c)

from django.template import Template, Context
raw_template = """<p>Dear {{ person_name }},</p>
...
... <p>Thanks for placing an order from {{ company }}. It's scheduled to
... ship on {{ ship_date|date:"F j, Y" }}.</p>
...
... {% if ordered_warranty %}
... <p>Your warranty information will be included in the packaging.</p>
... {% else %}
... <p>You didn't order a warranty, so you're on your own when
... the products inevitably stop working.</p>
... {% endif %}
...
... <p>Sincerely,<br />{{ company }}</p>"""
t = Template(raw_template)
import datetime
c = Context({'person_name': 'John Smith',
... 'company': 'Outdoor Equipment',
... 'ship_date': datetime.date(2009, 4, 2),
... 'ordered_warranty': False})
t.render(c)
u"<p>Dear John Smith,</p>\n\n<p>Thanks for placing an order from Outdoor
Equipment. It's scheduled to\nship on April 2, 2009.</p>\n\n\n<p>You
didn't order a warranty, so you're on your own when\nthe products
inevitably stop working.</p>\n\n\n<p>Sincerely,<br />Outdoor Equipment
</p>"

字典渲染

from django.template import Template, Context
person = {'name': 'Sally', 'age': '43'}
t = Template('{{ person.name }} is {{ person.age }} years old.')
c = Context({'person': person})
t.render(c)
u'Sally is 43 years old.'

日期渲染

from django.template import Template, Context
import datetime
d = datetime.date(1993, 5, 2)
d.year
Dear {{ person_name }},</p>
...
... <p>Thanks for placing an order from {{ company }}. It's scheduled to
... ship on {{ ship_date|date:"F j, Y" }}.</p>
...
... {% if ordered_warranty %}
... <p>Your warranty information will be included in the packaging.</p>
... {% else %}
... <p>You didn't order a warranty, so you're on your own when
... the products inevitably stop working.</p>
... {% endif %}
...
... <p>Sincerely,<br />{{ company }}</p>"""
>>> t = Template(raw_template)
>>> import datetime
>>> c = Context({'person_name': 'John Smith',
... 'company': 'Outdoor Equipment',
... 'ship_date': datetime.date(2009, 4, 2),
... 'ordered_warranty': False})
>>> t.render(c)
u"<p>Dear John Smith,</p>\n\n<p>Thanks for placing an order from Outdoor
Equipment. It's scheduled to\nship on April 2, 2009.</p>\n\n\n<p>You
didn't order a warranty, so you're on your own when\nthe products
inevitably stop working.</p>\n\n\n<p>Sincerely,<br />Outdoor Equipment
</p>"

字典渲染
>>> from django.template import Template, Context
>>> person = {'name': 'Sally', 'age': '43'}
>>> t = Template('{{ person.name }} is {{ person.age }} years old.')
>>> c = Context({'person': person})
>>> t.render(c)
u'Sally is 43 years old.'

日期渲染
>>> from django.template import Template, Context
>>> import datetime
>>> d = datetime.date(1993, 5, 2)
>>> d.year
1993
d.month
5
d.day
2
t = Template('The month is {{ date.month }} and the year is {{ date.year }}.')
c = Context({'date': d})
t.render(c)
u'The month is 5 and the year is 1993.'

类属性渲染

from django.template import Template, Context
class Person(object):
... def init(self, first_name, last_name):
... self.first_name, self.last_name = first_name, last_name
t = Template('Hello, {{ person.first_name }} {{ person.last_name }}.')
c = Context({'person': Person('John', 'Smith')})
t.render(c)
u'Hello, John Smith.'

数组、列表渲染

from django.template import Template, Context
t = Template('Item 2 is {{ items.2 }}.')
c = Context({'items': ['apples', 'bananas', 'carrots']})
t.render(c)
u'Item 2 is carrots.'

方法调用,不加括号

from django.template import Template, Context
person = {'name': 'Sally', 'age': '43'}
t = Template('{{ person.name.upper }} is {{ person.age }} years old.')
c = Context({'person': person})
t.render(c)
u'SALLY is 43 years old.'

属性

from django.template import Context
c = Context({"foo": "bar"})
c['foo']
'bar'
del c['foo']
c['foo']
Traceback (most recent call last):
...
KeyError: 'foo'
c['newvariable'] = 'hello'
c['newvariable']
'hello'

判断语句
{% if today_is_weekend %}
<p>Welcome to the weekend!</p>
{% endif %}

{% if today_is_weekend %}
<p>Welcome to the weekend!</p>
{% else %}
<p>Get back to work.</p>
{% endif %}

{% if athlete_list and coach_list %}
Both athletes and coaches are available.
{% endif %}

{% if not athlete_list %}
There are no athletes.
{% endif %}

{% if athlete_list or coach_list %}
There are some athletes or some coaches.
{% endif %}

{% if not athlete_list or coach_list %}
There are no athletes or there are some coaches.
{% endif %}

{% if athlete_list and not coach_list %}
There are some athletes and absolutely no coaches.
{% endif %}

多条件
{% if athlete_list %}
{% if coach_list or cheerleader_list %}
We have athletes, and either coaches or cheerleaders!
{% endif %}
{% endif %}

for语句
{% for athlete in athlete_list %}
<h1>{{ athlete.name }}</h1>
<ul>
{% for sport in athlete.sports_played %}
<li>{{ sport }}</li>
{% endfor %}
</ul>
{% endfor %}

典型table
{% for country in countries %}
<table>
{% for city in country.city_list %}
<tr>
<td>Country #{{ forloop.parentloop.counter }}</td>
<td>City #{{ forloop.counter }}</td>
<td>{{ city }}</td>
</tr>
{% endfor %}
</table>
{% endfor %}

变量比较
{% ifequal user currentuser %}
<h1>Welcome!</h1>
{% endifequal %}

{% ifequal section 'sitenews' %}
<h1>Site News</h1>
{% endifequal %}

{% ifequal section "community" %}
<h1>Community</h1>
{% endifequal %}

注释
{# This is a comment #}

{% comment %}
This is a
multi-line comment.
{% endcomment %}

过滤
{{ name|lower }}

{{ my_list|first|upper }}

获取前30个词
{{ bio|truncatewords:"30" }}

格式化日期
{{ pub_date|date:"F j, Y" }}

设置模板的路径:setting.py
TEMPLATE_DIRS = (
'/home/django/mysite/templates',
)

动态模板路径
import os.path

TEMPLATE_DIRS = (
os.path.join(os.path.dirname(file), 'templates').replace('\','/'),
)

get_template动态加载模板
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
import datetime

def current_datetime(request):
now = datetime.datetime.now()
t = get_template('current_datetime.html')
html = t.render(Context({'current_date': now}))
return HttpResponse(html)

render_to_response:::::::
from django.shortcuts import render_to_response
import datetime

def current_datetime(request):
now = datetime.datetime.now()
return render_to_response('current_datetime.html', {'current_date': now})

内嵌模板:
{% include 'nav.html' %}
{% include "nav.html" %}

extends模板的用法
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<h1>My helpful timestamp site</h1>
{% block content %}{% endblock %}
{% block footer %}



<p>Thanks for visiting my site.</p>
{% endblock %}
</body>
</html>

{% extends "base.html" %}

{% block title %}The current time{% endblock %}

{% block content %}
<p>It is now {{ current_date }}.</p>
{% endblock %}

{% extends "base.html" %}

{% block title %}Future time{% endblock %}

{% block content %}
<p>In {{ hour_offset }} hour(s), it will be {{ next_time }}.</p>
{% endblock %}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值