Search code examples
twigternary-operatorstring-concatenation

Ternary concatenation in Twig


Is it possible to use ternary operator in Twig when concatenating one string to another if some condition is true?

This works for me:

{% set a = 'initial' %}
{% if foo == bar %}
     {% set a = a ~ ' concatenate' %}
{% endif %}
<p>{{ a }}</p>

But when I try to simplify it like this, it throws an error:

{% set a = 'initial' ~ (foo == bar) ? ' concatenate' : '' %}
<p>{{ a }}</p>

Am I doing something wrong or this simplification is simply not possible in Twig?


Solution

  • due to the order of precedence you'll need to add parentheses,
    {% set a = 'initial' ~ ((foo == bar) ? ' concatenate' : '') %}


    If the 2nd part is empty you can even omit it e.g.

    {% set b = 'initial' ~ ((foo == foo) ? ' concatenate') %}
    

    twigfiddle