phptwigshort-circuiting

How to check for null in Twig?


What construct should I use to check whether a value is NULL in a Twig template?


Solution

  • Depending on what exactly you need:

    {% if var is null %}
        {# do something #}
    {% endif %}
    
    {% if var is not defined %}
        {# do something #}
    {% endif %}
    

    Additionally the is sameas test, which does a type strict comparison of two values, might be of interest for checking values other than null (like false):

    {% if var is sameas(false) %}
        {# do something %}
    {% endif %}