跳到主要内容

Jinja2 控制语句

前言​

模板中的控制语句:条件判断(if)和循环(for),对应 Python 中的 if 和 for。

if 语句​

{% if score >= 90 %}
<p>优秀</p>
{% elif score >= 60 %}
<p>及格</p>
{% else %}
<p>不及格</p>
{% endif %}

支持的表达式:

{% if user and user.is_active %}      {# and / or / not #}
{% if name in users %} {# in #}
{% if a == b or c != d %} {# 比较 #}
{% if value is defined %} {# 测试器 #}
{% endif %}

for 循环​

<ul>
{% for user in users %}
<li>{{ user.name }}</li>
{% else %}
<li>没有用户</li>
{% endfor %}
</ul>

{% else %} 在循环体一次都没有执行时输出。

循环过滤​

{# 只输出偶数 #}
{% for n in range(10) if n % 2 == 0 %}
{{ n }}
{% endfor %}

嵌套循环与循环变量​

{% for row in matrix %}
{% for cell in row %}
({{ loop.index0 }}, {{ loop.index0 }}) = {{ cell }}
{% endfor %}
{% endfor %}

loop 常用属性:index、index0、first、last、revindex、length。