Boolean Logic

In Twig, it is not possible to combine expressions with standard programming synax like '||', '&&' and '!'.  Instead it is necessary to use 'and', 'or' and 'not':

{% if not var and ( foo == 5 or foo == 10 ) %} 

The following comparison operators are supported in any expression: ==!=<>>=, and <=.

Besides PHP classic comparison operators, Twig also supports a shortcut notation when you want to test a value in a range:

{% if 1 < foo < 4 %}foo is between 1 and 4{% endif %}

Other Operators

The following operators are very useful but don't fit into any of the other two categories:

  • in (new in Twig 0.9.5): Performs containment test. Returns true if the left operand is contained in the right. {{ 1 in [1, 2, 3] }} would for example return true. To perform a negative test, the whole expression should be prefixed with not ({{ not 1 in [1, 2, 3] }} would return false).

  • .. (new in Twig 0.9.5): Creates a sequence based on the operand before and after the operator (see the for tag for some usage examples).

  • |: Applies a filter.

  • ~: Converts all operands into strings and concatenates them. {{ "Hello " ~ name ~ "!" }} would return (assuming name is 'John')Hello John!.

  • .[]: Gets an attribute of an object.

  • ?:: Twig supports the PHP ternary operator:

    {{ foo ? 'yes' : 'no' }}