if
Twig 中的 if
语句与 PHP 的 if 语句类似。
在最简单的形式中,您可以使用它来测试表达式是否评估为 true
1 2 3
{% if online == false %}
<p>Our website is in maintenance mode. Please, come back later.</p>
{% endif %}
您还可以测试序列或映射是否不为空
1 2 3 4 5 6 7
{% if users %}
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
{% endif %}
注意
如果您想测试变量是否已定义,请改用 if users is defined
。
您还可以使用 not
来检查评估为 false
的值
1 2 3
{% if not user.subscribed %}
<p>You are not subscribed to our mailing list.</p>
{% endif %}
对于多个条件,可以使用 and
和 or
1 2 3
{% if temperature > 18 and temperature < 27 %}
<p>It's a nice day for a walk in the park.</p>
{% endif %}
对于多个分支,可以像在 PHP 中一样使用 elseif
和 else
。您也可以在那里使用更复杂的 expressions
1 2 3 4 5 6 7
{% if product.stock > 10 %}
Available
{% elseif product.stock > 0 %}
Only {{ product.stock }} left!
{% else %}
Sold-out!
{% endif %}
注意
确定表达式是 true
还是 false
的规则与 PHP 中的规则相同;以下是边缘情况规则
值 | 布尔值评估 |
---|---|
空字符串 | false |
数值零 | false |
NAN (非数字) | true |
INF (无穷大) | true |
仅包含空格的字符串 | true |
字符串 "0" 或 '0' | false |
空序列 | false |
空映射 | false |
null | false |
非空序列 | true |
非空映射 | true |
对象 | true |