How to check for null in Twig?

前端 未结 8 881
执笔经年
执笔经年 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 18:04

    I don't think you can. This is because if a variable is undefined (not set) in the twig template, it looks like NULL or none (in twig terms). I'm pretty sure this is to suppress bad access errors from occurring in the template.

    Due to the lack of a "identity" in Twig (===) this is the best you can do

    {% if var == null %}
        stuff in here
    {% endif %}
    

    Which translates to:

    if ((isset($context['somethingnull']) ? $context['somethingnull'] : null) == null)
    {
      echo "stuff in here";
    }
    

    Which if your good at your type juggling, means that things such as 0, '', FALSE, NULL, and an undefined var will also make that statement true.

    My suggest is to ask for the identity to be implemented into Twig.

    0 讨论(0)
  • 2020-11-30 18:07

    Also if your variable is an ARRAY, there are few options too:

    {% if arrayVariable[0] is defined %} 
        #if variable is not null#
    {% endif %}
    

    OR

    {% if arrayVariable|length > 0 %} 
        #if variable is not null# 
    {% endif %}
    

    This will only works if your array is defined AND is NULL

    0 讨论(0)
提交回复
热议问题