树枝:具有多种条件的IF

2022-08-30 06:53:58

看来我对树枝if语句有问题。

{%if fields | length > 0 || trans_fields | length > 0 -%}

错误是:

Unexpected token "punctuation" of value "|" ("name" expected) in 

我不明白为什么这不起作用,就像树枝和所有的管道都丢失了一样。

我试过这个:

{% set count1 = fields | length %}
{% set count2 = trans_fields | length %}
{%if count1 > 0 || count2 > 0 -%}

但如果也失败了。

然后尝试了这个:

{% set count1 = fields | length > 0 %}
{% set count2 = trans_fields | length > 0 %}
{%if count1 || count2 -%}

它仍然不起作用,每次都出现相同的错误...

所以。。。这就引出了一个非常简单的问题:Twig是否支持多个条件IF?


答案 1

如果我没记错的话,Twig不支持和运算符,而是需要和分别使用。我还会使用括号来更清楚地表示这两个语句,尽管这在技术上不是必需的。||&&orand

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

表达 式

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

对于更复杂的操作,最好将各个表达式括在括号中以避免混淆:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

答案 2

用于多个条件对我来说也不起作用,但是确实有效 - 实际上这似乎是一个错误。!===

可能的解决方法。

{% if key not in ['string1', 'string2'] %}
// print something
{% endif %}

推荐