if

这个 if Twig中的语句与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 %}

对于多种情况, andor 可用于:

1
2
3
{% if temperature > 18 and temperature < 27 %}
    <p>It's a nice day for a walk in the park.</p>
{% endif %}

对于多个分支 elseifelse 可以像在PHP中一样使用。你可以用更复杂的 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 %}

注解

确定表达式是否为 truefalse 与PHP中的相同;以下是边缘情况规则:

价值 布尔运算
空字符串
数字零
南(不是数字)
INF(无穷大)
纯空白字符串
字符串“0”或“0”
空数组
无效的
非空数组
对象