控制语句
所有的控制语句都是放在{% ... %}
中,并且有一个语句{% endxxx %}
来进行结束,Jinja
中常用的控制语句有if/for..in..
,现对他们进行讲解:
if
:if语句和python
中的类似,可以使用>,<,<=,>=,==,!=
来进行判断,也可以通过and,or,not,()
来进行逻辑合并操作,以下看例子:{% if kenny.sick %} Kenny is sick. {% elif kenny.dead %} You killed Kenny! You bastard!!! {% else %} Kenny looks okay --- so far {% endif %}
for...in...
:for
循环可以遍历任何一个序列包括列表、字典、元组。并且可以进行反向遍历,以下将用几个例子进行解释:普通的遍历:
<ul> {% for user in users %} <li>{{ user.username|e }}</li> {% endfor %} </ul>
遍历字典:
<dl> {% for key, value in my_dict.iteritems() %} <dt>{{ key|e }}</dt> <dd>{{ value|e }}</dd> {% endfor %} </dl>
如果序列中没有值的时候,进入
else
:<ul> {% for user in users %} <li>{{ user.username|e }}</li> {% else %} <li><em>no users found</em></li> {% endfor %} </ul>
并且
Jinja
中的for
循环还包含以下变量,可以用来获取当前的遍历状态:| 变量 | 描述 | | --- | --- | | loop.index | 当前迭代的索引(从1开始) | | loop.index0 | 当前迭代的索引(从0开始) | | loop.first | 是否是第一次迭代,返回True或False | | loop.last | 是否是最后一次迭代,返回True或False | | loop.length | 序列的长度 |
另外,不可以使用
continue
和break
表达式来控制循环的执行。