Is it possible to use ternary operators in twig template? Now, for adding some class to DOM element depend on some condition I do like this:
{%if ability.id in company_abilities%}
<tr class="selected">
{%else%}
<tr>
{%endif%}
Instead of
<tr class="<?=in_array($ability->id, $company_abilities) ? 'selected' : ''?>">
in native php template engine.
The ternary operator is documented under 'other operators'
The ternary operator (
?:
)Support for the extended ternary operator was added in Twig 1.12.0.
Case #1
Snippet:
Evaluates:
Case #2
Snippet:
or
Evaluates:
Case #3
Snippet:
or
Evaluates:
The null-coalescing operator (
??
)Case #1
Snippet:
Evaluates:
Note: this is slightly different from
{{ foo|default('no') }}
, since the latter will be triggered also from empty values like''
.You can use shorthand syntax as of Twig 1.12.0