1

From this question we know how to use a ternary operator to output conditional text: Is there a Twig shorthand syntax for outputting conditional text

Example:

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

How can we use a ternary operator to conditionally set a variable, without outputting it directly?

Robin Bastiaan
  • 572
  • 2
  • 8
  • 21

2 Answers2

5

You can use:

{% set foo = foo ? 'yes' : 'no' %}

Note you need to use {% %} instead of {{ }} and add the set keyword.

Robin Bastiaan
  • 572
  • 2
  • 8
  • 21
2

You try

{{ foo is defined ? 'yes' : 'no' }}

or

{% if foo is defined %}
    {{ foo ? 'yes' : 'no' }}
{% endif %}
poppies
  • 142
  • 6