1

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?

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

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.