{% for %} 和 {% endfor %} 标签将遍历集合中的每个值。集合可以是数组,也可以是实现了 Traversable 接口的对象。
<ul>
{% for user in users %}
<li>{{ user.username }}</li>
{% endfor %}
</ul>你也可以同时访问键和值:
<ul>
{% for key, user in users %}
<li>{{ key }}: {{ user.username }}</li>
{% endfor %}
</ul>如果集合为空,你可以使用 else 渲染一个替代块:
<ul>
{% for user in users %}
<li>{{ user.username }}</li>
{% else %}
<li><em>未找到用户</em></li>
{% endfor %}
</ul>如果你确实需要遍历数字集合,你可以使用 .. 运算符:
{% for i in 0..10 %}
- {{ i }}
{% endfor %}上述代码片段将打印从 0 到 10 的所有数字。
它也可以用于字母:
{% for letter in 'a'..'z' %}
- {{ letter }}
{% endfor %}.. 运算符可以在两边接受任何表达式:
{% for letter in 'a'|upper..'z'|upper %}
- {{ letter }}
{% endfor %}与 PHP 不同,在循环中没有 break 或 continue 函数,但你仍然可以筛选集合。以下示例跳过所有不活跃的 users。
<ul>
{% for user in users %}
{% if user.active %}
<li>{{ user.username }}</li>
{% endif %}
{% endfor %}
</ul>在 for 循环块内部,你可以访问一些特殊变量:
| 变量 | 描述 |
|---|---|
loop.index | 循环的当前迭代。(从 1 开始索引) |
loop.index0 | 循环的当前迭代。(从 0 开始索引) |
loop.revindex | 从循环结束开始的迭代次数(从 1 开始索引) |
loop.revindex0 | 从循环结束开始的迭代次数(从 0 开始索引) |
loop.first | 如果是第一次迭代则为 True |
loop.last | 如果是最后一次迭代则为 True |
loop.length | 集合中的项目数量 |
loop.parent | 父上下文 |
{% for user in users %}
{{ loop.index }} - {{ user.username }}
{% endfor %}