The conditional operator – also known as the ternary operator – is an alternative form of the if/else statement that helps you to write conditional code blocks in a more concise way. First, you need to write a conditional expression that evaluates into either true or false .
Moreover, as has been pointed out, at the byte code level there's really no difference between the ternary operator and if-then-else. As in the above example, the decision on which to choose is based wholly on readability.
Ternary operators are also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5. It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.
{{ (ability.id in company_abilities) ? 'selected' : '' }}
The ternary operator is documented under 'other operators'
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' : '' }}
Support for the extended ternary operator was added in Twig 1.12.0.
If foo
echo yes
else echo no
:
{{ foo ? 'yes' : 'no' }}
If foo
echo it, else echo no
:
{{ foo ?: 'no' }}
or
{{ foo ? foo : 'no' }}
If foo
echo yes
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') }}
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' }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With