Twig: IF с несколькими условиями - программирование
Подтвердить что ты не робот

Twig: IF с несколькими условиями

Кажется, у меня проблема с выражением twig 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 -%}

но if также не работает.

Тогда попробовал это:

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

И он по-прежнему не работает, такая же ошибка каждый раз...

Итак... это привело меня к очень простому вопросу: поддерживает ли Twig несколько условий IF?

4b9b3361

Ответ 1

Если я правильно помню, Twig не поддерживает операторы || и &&, но требует использования or и and соответственно. Я также использовал бы круглые скобки для более четкого обозначения этих двух утверждений, хотя это технически не требуется.

{%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)) %}