веточка: ЕСЛИ с несколькими условиями - PullRequest
111 голосов
/ 05 декабря 2011

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

276 голосов
/ 05 декабря 2011

Если я правильно помню, 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)) %}
...