DTL模板语言中,{% for %}标签用于实现循环操作
arr=range(10)
{% for i in arr%}
i --
{% endfor %}
结果:0 -- 1 -- 2 -- 3 -- 4 --5 -- 6 -- 7-- 8 --9
添加reversed进行反响迭代
arr=range(10)
{% for i in arr reversed %}
i --
{% endfor %}
结果:9 -- 8 -- 7 -- 6 -- 5 -- 4 -- 3 -- 2 -- 1 --0
同其他语言一样,{% for %}标签可以嵌套使用
迭代列表:(字典同样可以使用)
a=[(1,1),(2,2),(3,3)]
{% for x,y in a%}
({{x}},{{y}})
{% endfor %}
结果:(1,1)(2,2)(3,3)
通常,迭代列表之前要检查列表的大小,如果未空,显示一些特殊的文字
{% if lista %}
{% for x,y in lista %}
({{x}},{{y}})
{% endfor%}
{% else %}
<p>There is nothing in the List</p>
{% endif %}
结果:There is nothing in the List #因为没有给Lista赋值,所以此时它是不存在,为空的
当然,{% for %}标签支持一个可选的{% empty %}字句,用于定义列表为空时显示的内容。下面这个例子与上面一个的例子等效
{% for x,y in lista%}
({{x}},{{y}})
{% empty %}
<p>There is nothing in the List</p>
{% endfor %}
注意:{% for %}标签没有break 或者是 continue ,不能退出循环或者立即返回到循环的额开头
forloop:
这个模板变量有几个属性,通过他们可以获知循环进程的一些信息:
forloop.counter:值为一个整数,属性值从1开始,即第一次循环开始,值为1
forloop.counter0:与forloop.counter相似,不过是从0开始的
a=range(10)
{% for item in a %}
<p>{{forloop.counter}}:{{item}}</p>
{% endfor %}
forloop.revcounter:值为一个整数,表示循环中剩余的元素数量。第一次循环时,其值为所有蒜素的个数,最后一次为1
forloop.revcounter0:与forloop.revcounter相似,索引是基于0的,第一次为总元素个数-1,最后一次为0
forloop.first:是一个布尔值,第一次循环为ture,需要特殊处理第一个元素时很方便:
forloop.last:和forloop.first相似,不过是最后一次循环时为真,通常运用在在一组链接之间防放置管道符号
{% for link in links %}
{{link}}{% if not forloop.last %} | {% endif %}
{% endfor %}
结果:link1 | link2 |link3 |link4
forloop.parentloop:用于引用父级的forloop对象:
{% 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>
<td></td>
</tr>
{% endfor %}
</table>
{% endfor %}
Attention:forloop只可以在for循环中使用,一旦遇见endfor,forloop会随之消失