twig: IF with multiple conditions

PhpTwigConditional Operator

Php Problem Overview


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 ?

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFMaz008View Question on Stackoverflow
Solution 1 - PhpBen SwinburneView Answer on Stackoverflow
Solution 2 - PhpdelmarrView Answer on Stackoverflow