Robin Bastiaan
Robin Bastiaan

Reputation: 702

Twig shorthand conditionally set variable

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?

Upvotes: 1

Views: 4494

Answers (2)

poppies
poppies

Reputation: 120

You try

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

or

{% if foo is defined %}
    {{ foo ? 'yes' : 'no' }}
{% endif %}

Upvotes: 2

Robin Bastiaan
Robin Bastiaan

Reputation: 702

You can use:

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

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

Upvotes: 5

Related Questions