You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Timber/Twig中If语句无法正常运行,or运算符使用问题如何解决?

问题原因

你写的条件判断存在逻辑错误,并非or运算符本身故障,核心问题是多条件判断的语法不符合Twig规则:
你给出的代码{% if post.product_status != 'In Stock' or 'In Transit' %}拆解后实际执行逻辑为:

  • 第一个判断项:post.product_status != 'In Stock',按实际值返回布尔结果
  • 第二个判断项:直接校验'In Transit'字符串的布尔值,非空字符串在Twig中恒为true
    因此整个判断条件会永远返回true,无法匹配你的预期逻辑。
正确实现方案

你可以根据自身需求选择对应的写法:

需求1:状态既不是「库存中」也不是「运输中」时执行代码

需使用and运算符同时满足两个不等条件,两种写法可选:

  • 完整条件写法
{% if post.product_status != 'In Stock' and post.product_status != 'In Transit' %}
{# 执行你的代码 #}
{% endif %}
  • 更简洁的not in写法(后续新增状态时修改更方便)
{% if post.product_status not in ['In Stock', 'In Transit'] %}
{# 执行你的代码 #}
{% endif %}

需求2:状态是「库存中」或「运输中」时执行代码

如果你的实际需求是匹配这两个状态中的任意一种就执行代码,两种写法可选:

  • 完整条件写法
{% if post.product_status == 'In Stock' or post.product_status == 'In Transit' %}
{# 执行你的代码 #}
{% endif %}
  • 更简洁的in写法
{% if post.product_status in ['In Stock', 'In Transit'] %}
{# 执行你的代码 #}
{% endif %}

内容的提问来源于stack exchange,提问作者ShrockCo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 16:21:03