Twig中if语句用{% if %}{% endif %}标签块,不支持括号语法和三元运算符;需注意变量真假值差异、空值防护(is defined/default)、多条件用and/or/not且无括号优先级。

Twig 中 if 语句的基本写法
Twig 的 if 不是 PHP 那种括号语法,也不支持三元运算符缩写(?:)直接嵌入判断逻辑——它用的是明确的标签块。最简形式就是:{% if user %}欢迎回来{% endif %}。这里的 user 是变量,Twig 会自动判断是否为“真值”:非空字符串、非零数字、非空数组、非 null 对象都算 true。
常见真假判断陷阱和等值比较
新手常以为 {% if status == 'active' %} 就够了,但实际中容易漏掉 null 或类型不一致问题。Twig 默认宽松比较,但建议显式处理边界情况:
-
{% if status is defined and status == 'active' %}—— 防止status变量未传入导致报错 -
{% if user.roles is iterable and 'ROLE_ADMIN' in user.roles %}—— 判断数组/集合时别直接用is not empty,因为 null 也会触发异常;is iterable更安全 -
{% if product.price|default(0) > 100 %}—— 数值比较前用|default过滤 null,避免>操作符在 null 上失败
多条件与否定写法怎么组织
Twig 不支持 && || 符号,必须用英文单词 and / or / not,且优先级固定(not 最高,and 次之,or 最低),没有括号改变顺序的能力。所以复杂逻辑要拆开或提前计算:
- ✅ 推荐:
{% if user and user.isVerified() and not user.isBanned() %} - ❌ 危险:
{% if user.isVerified() or user.role == 'admin' and user.age > 18 %}—— 实际等价于user.isVerified() or (user.role == 'admin' and user.age > 18),但人眼容易误读 - ? 替代方案:把复合判断逻辑移到 Controller 或自定义 Twig 函数里,模板只做简单分支
空数组、空字符串、null 的真实行为差异
Twig 对“空”的判定比 PHP 更激进。比如空字符串 ''、数值 0、字符串 '0' 在 {% if var %} 中表现不同:
-
''→ false -
0→ false -
'0'→ true(字符串非空) -
[](空数组)→ false -
null→ false,但直接访问user.name会报Impossible to access an attribute ("name") on a null variable
所以涉及对象属性访问,务必先用 is defined 或 is null 守卫,或者统一用 user.name|default('') 配合后续判断。
真正麻烦的不是语法本身,而是模板里混着业务逻辑判断时,真假值来源不可控——变量可能来自 API、表单、Session 或默认值,每个环节都可能悄悄塞进一个 '0' 或 []。写 if 前,先确认这个变量到底可能是什么。

















