Pregunta

Parece que tengo un problema con una declaración de ramita if.

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

El error es:

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

No puedo entender por qué esto no funciona, es como si Twig se perdiera con todas las tuberías.

He probado esto:

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

Pero el si también fallan.

Luego probé esto:

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

Y todavía no funciona, el mismo error cada vez ...

Entonces ... eso me llevó a una pregunta realmente simple: ¿Twig admite múltiples condiciones si?

¿Fue útil?

Solución

Si recuerdo correctamente, Twig no admite || y && operadores, pero requiere or y and para ser utilizado respectivamente. También usaría paréntesis para denotar las dos declaraciones más claramente, aunque esto no es técnicamente un requisito.

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

Expresiones

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.

Para operaciones más complejas, puede ser mejor envolver expresiones individuales entre paréntesis para evitar confusiones:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top