如果 Timber/Twig 中的语句对我不起作用

If Statement in Timber/Twig not working for me

所以如果我有 {% if post.product_status != 'In Stock' or 'In Transit' %} {# execute my code #} {% endif %} 这将不起作用是不是我使用 or 运算符有问题?我应该改用什么?

您的语句将始终 return 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 %}