How to check for null in Twig?

前端 未结 8 929
执笔经年
执笔经年 2020-11-30 17:21

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

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 17:53

    Depending on what exactly you need:

    • is null checks whether the value is null:

      {% if var is null %}
          {# do something #}
      {% endif %}
      
    • is defined checks whether the variable is defined:

      {% 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 %}
    

提交回复
热议问题