Twig ternary operator, Shorthand if-then-else
Does Twig support ternary (shorthand if-else) operator?
I need some conditional logic like:
{%if ability.id in company_abilities %}
<tr class="selected">
{%else%}
<tr>
{%endif%}
but using shorthand in Twig.
Solution 1:
{{ (ability.id in company_abilities) ? 'selected' : '' }}
The ternary operator is documented under 'other operators'
Solution 2:
You can use shorthand syntax as of Twig 1.12.0
{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}
Solution 3:
Support for the extended ternary operator was added in Twig 1.12.0.
-
If
foo
echoyes
else echono
:{{ foo ? 'yes' : 'no' }}
-
If
foo
echo it, else echono
:{{ foo ?: 'no' }}
or
{{ foo ? foo : 'no' }}
-
If
foo
echoyes
else echo nothing:{{ foo ? 'yes' }}
or
{{ foo ? 'yes' : '' }}
-
Returns the value of
foo
if it is defined and not null,no
otherwise:{{ foo ?? 'no' }}
-
Returns the value of
foo
if it is defined (empty values also count),no
otherwise:{{ foo|default('no') }}
Solution 4:
If the price exists from the database for example then print (Price is $$$) else print (Not Available) and ~
for the concatenation in Twig
.
{{ Price is defined ? 'Price is '~Price : 'Not Available' }}