Twig tip: Ternary operator with an undefined variable

You can use the default filter in combination with the ternary operator :? on a variable within a Slim Twig template when the variable is undefined:

{{ myVar|default ? '' : ' class="myClass"'}}

or in an if statement:

{% if myVar|default %}
  ...
{% endif %}

When the variable is undefined and should not be an empty string:

{{ myVar|default('') == '' ? '' : ' class="myClass"'}}

Leave a comment

Your email address will not be published. Required fields are marked *