问题描述
所以,如果我有一个 {% if post.product_status != 'In Stock' or 'In Transit' %}
{# 执行我的代码 #} {% endif %}
什么会不起作用,我使用 or
运算符有什么问题吗?我应该改用什么?
解决方法
您的语句将始终返回 true
,因为 In Transit
- 它是非空字符串。
你可以测试一下
{% if 'In Transit' %}
// Will be executed
{% endif %}
{% if false or 'In Transit' %}
// Will be executed because one of condition is true
{% endif %}
{% if post.product_status != 'In Stock' or post.product_status != 'In Transit' %}
// Will be executed. Why? Even if your status is not 'In Stock' second part of condition will return true
{% endif %}
{% if post.product_status != 'In Stock' and post.product_status != 'In Transit' %}
// Will NOT be executed if status is 'In Stock' or 'In Transit'. Both conditions are false now
{% endif %}
此条件变得非常难以理解,因此最好将其更改为。让我们检查我们的状态值是否存在于排除状态数组中
{% set excluded = [ 'In Stock','In Transit','Any New Status Here' ] %}
{% if post.product_status not in excluded %}
// Code to execute
{% endif %}