144

It seem I have problem with a twig if statement.

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

The error is:

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

I can't understand why this doesn't work, it's like if twig was lost with all the pipes.

I've tried this :

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

but the if also fail.

Then tried this:

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

And it still doesn't work, same error every time ...

So... that lead me to a really simple question: does Twig support multiple conditions IF ?

2 Answers 2

333

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%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. 

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %} 
Sign up to request clarification or add additional context in comments.

8 Comments

And of course I had no chance of finding that wonderful and time-saving table when looking at the IF documentation : twig.sensiolabs.org/doc/tags/if.html Thanks for the solution !
They tend to use the wiki on github to more thoroughly document their code. That table comes from here
Using != didn't seem to work for me (may be a bug?): {% if (key != 'string1') or (key != 'string2') or (key != 'string3') %} so I had to use (key == 'stringN') for all of them and put what I needed in the 'else' statement
You need to use the not operator to negate the expression.
you forgot the ternary operator ?
|
3

Using != for multiple conditions does not work for me either, however == does work - indeed this seems like a bug.

Possible work around.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.