web-dev-qa-db-fra.com

twig: SI avec plusieurs conditions

Il semble que j'ai un problème avec une déclaration twig if.

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

L'erreur est:

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

Je ne comprends pas pourquoi cela ne fonctionne pas, c'est comme si twig était perdu avec tous les tuyaux.

J'ai essayé ceci:

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

mais si aussi échouer.

Alors essayé ceci:

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

Et ça ne marche toujours pas, même erreur à chaque fois ...

Donc ... cela me conduit à une question très simple: est-ce que Twig prend en charge plusieurs conditions SI?

114
FMaz008

Si je me souviens bien, Twig ne prend pas en charge les opérateurs || et &&, mais requiert l'utilisation de or et and. J'utiliserais aussi des parenthèses pour indiquer plus clairement les deux déclarations, bien que ce ne soit techniquement pas une obligation.

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

Expressions

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.

Pour des opérations plus complexes, il peut être préférable de mettre les expressions individuelles entre parenthèses pour éviter toute confusion:

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