Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.template import Context, Template
>>> t = Template('My name is {{ name }}.')
>>> c = Context({'name': 'Stephane'})
>>> t.render(c)
'My name is Stephane.'
这就是使用Django模板系统的基本规则:写模板,创建Template对象,创建Context,调用render()方法。 深度变量的查找
我们通过context传递的简单参数值主要是字符串,还有一个datetime.date范例。然而,模板系统能够非常简洁地处理更加复杂的数据结构,例如list、dictionary和自定义的对象。
在Django模板中遍历复杂数据结构的关键是句点字符(.)。
最好是用几个例子来说明一下。 比如,假设你要向模板传递一个Python字典,要通过字典键访问该字典的值,可使用一个句点:
>>> 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)
'Sally is 43 years old.'
点语法也可以用来引用对象的方法。 例如,每个Python字符串都有upper()和isdigit()方法,你在模板中可以使用同样的句点语法来调用它们:
>>> from django.template import Template, Context
>>> t = Template('{{ var }} -- {{ var.upper }} -- {{ var.isdigit }}')
>>> t.render(Context({'var': 'hello'}))
'hello -- HELLO -- False'
>>> t.render(Context({'var': '123'}))
'123 -- 123 -- True'
句点也可用于访问列表索引,例如:
>>> from django.template import Template, Context
>>> t = Template('Item 2 is {{ items.2 }}.')
>>> c = Context({'items': ['apples', 'bananas', 'carrots']})
>>> t.render(c)
'Item 2 is carrots.' 当模板系统在变量名中遇到点时,按照以下顺序尝试进行查找:
字典类型查找(比如foo["bar"])
属性查找(比如foo.bar)
方法调用(比如foo.bar())
列表类型索引查找(比如foo[bar])
模板标签 if/else
{ % if % }标签检查一个变量的值是否为真或者等于另外一个值,如果为真,系统会执行{ % if % }和{ %endif % }之间的代码块,例如:
{% if today_is_weekend %}
<p>Welcome to the weekend!</p>
{% endif %}
{ % else % }标签是可选的:
如果不为真则执行{ % else % }和{ % endif % }之间的代码块
{ % if % }标签不允许在同一个标签中同时使用and和or,因为逻辑上可能模糊的,比如这样的代码是不合法的:
{% if athlete_list and coach_list or cheerleader_list %} 系统不支持用圆括号来组合比较操作,如果你确实需要用到圆括号来组合表达你的逻辑式,考虑将它移到模板之外处理,然后以模板变量的形式传入结果吧,或者,仅仅用嵌套的{ % if % }标签替换吧,就像这样:
{% if athlete_list %}
{% if coach_list or cheerleader_list %}
We have athletes, and either coaches or cheerleaders!
{% endif %}
{% endif %}
多次使用同一个逻辑操作符是没有问题的,但是我们不能把不同的操作符组合起来。 例如,这是合法的:
{% if athlete_list or coach_list or parent_list or teacher_list %} 并没有{ % elif % }标签,使用嵌套的{ % if % }标签来达成同样的效果:
{% if athlete_list %}
<p>Here are the athletes: {{ athlete_list }}.</p>
{% else %}
<p>No athletes are available.</p>
{% if coach_list %}
<p>Here are the coaches: {{ coach_list }}.</p>
{% endif %}
{% endif %}
一定要用{ % endif % }关闭每一个{ % if % }标签
for
{ % for % }允许我们在一个序列上迭代,与Python的 for 语句的情形类似,循环语法是for X in Y,Y是要迭代的序列而X是在每一个特定的循环中使用的变量名称。每一次循环中,模板系统会渲染在{ % for % } 和{ % endfor % }之间的所有内容。
例如创建一个运动员列表athlete_list变量,给标签增加一个reversed使得该列表被反向迭代,显示这个列表
<ul>
{% for athlete in athlete_list reversed %}
<li>{{ athlete.name }}</li>
{% endfor %}
</ul>
在执行循环之前先检测列表的大小为空时输出一些特别的提示:
{% for athlete in athlete_list %}
<p>{{ athlete.name }}</p>
{% else %}或者{% empty %}
<p>There are no athletes. Only computer programmers.</p>