Twig ternary operator, Shorthand if-then-else

PhpTwigConditional Operator

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

{{ (ability.id in company_abilities) ? 'selected' : '' }}

The ternary operator is documented under 'other operators'

Solution 2 - Php

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 - Php

Support for the extended ternary operator was added in Twig 1.12.0.

  1. If foo echo yes else echo no:

     {{ foo ? 'yes' : 'no' }}
    
  2. If foo echo it, else echo no:

     {{ foo ?: 'no' }}
    

or

    {{ foo ? foo : 'no' }}

3. If foo echo yes else echo nothing:

    {{ foo ? 'yes' }}

or

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

4. Returns the value of foo if it is defined and not null, no otherwise:

    {{ foo ?? 'no' }}

5. Returns the value of foo if it is defined (empty values also count), no otherwise:

    {{ foo|default('no') }}

Solution 4 - Php

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' }}

Solution 5 - Php

I just used a as a general variable name. You can also use endless if else like this:

{{ a == 1 ? 'first' : a == 2 ? 'second' : 'third' }}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMelibornView Question on Stackoverflow
Solution 1 - PhpBen SwinburneView Answer on Stackoverflow
Solution 2 - PhpmgalicView Answer on Stackoverflow
Solution 3 - PhpPmpr.irView Answer on Stackoverflow
Solution 4 - PhpL3xpertView Answer on Stackoverflow
Solution 5 - PhpWebManView Answer on Stackoverflow