Django:模板中的循环【for】
【for】循环的有用内置变量:
for循环的内置变量 | 说明 |
forloop.counter | 索引从【1】开始计算 |
forloop.counter0 | 索引从【0】开始计算 |
forloop.revcounter | 索引从最大长度到【1】 |
forloop.revcounter0 | 索引从最大长度到【0】 |
forloop.first | 如果是第一项,则返回【true】 |
forloop.last | 如果是最后一项,则返回【true】 |
forloop.parentloop | 用在嵌套的【loop循环】中,用于获取上一层循环的【forloop】 |
当循环的列表可能为空的时候,可以通过【{% empty %}】进行判断,如下:
1 2 3 4 5 6 7 |
<ul> {% for item in list %} <li>{{ item.name }}</li> {% empty %} <li>循环列表为空</li> {% endfor %} </ul> |
上面的代码高亮的插件有问题,但是语法的意思表达清楚了。