| 变量 | 描述 |
|---|---|
| forloop.counter | 索引从 1 开始算 |
| forloop.counter0 | 索引从 0 开始算 |
| forloop.revcounter | 索引从最大长度到 1 |
| forloop.revcounter0 | 索引从最大长度到 0 |
| forloop.first | 当遍历的元素为第一项时为真 |
| forloop.last | 当遍历的元素为最后一项时为真 |
| forloop.parentloop |
用在嵌套的 for 循环中, 获取上一层 for 循环的 forloop |
也许有的小伙伴对template for的用法不是很明确,借着这个机会,今天来讲讲新朋友template for循环。
当列表为空或者非空时执行不同操作:
{% for item in list %}
...
{% empty %}
...
{% endfor %}
使用forloop.counter访问循环的次数,下面这段代码依次输出循环的次数,从1开始计数:
{% for item in list %}
...
{{ forloop.counter }}
...
{% endfor %}
从0开始计数:
{% for item in list %}
...
{{ forloop.counter0 }}
...
{% endfor %}
判断是否是第一次循环:
{% for item in list %}
...
{% if forloop.first %}
This is the first round.
{% endif %}
...
{% endfor %}
判断是否是最后一次循环:
{% for item in list %}
...
{% if forloop.last %}
This is the last round.
{% endif %}
...
{% endfor %}
逆向循环:
{% for item in list reversed %}
{{ item }}
{% endfor %}
到此这篇关于Django中template for如何使用方法的文章就介绍到这了,更多相关Django template for内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!