How to check for null in Twig?

前端 未结 8 930
执笔经年
执笔经年 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:49

    Without any assumptions the answer is:

    {% if var is null %}
    

    But this will be true only if var is exactly NULL, and not any other value that evaluates to false (such as zero, empty string and empty array). Besides, it will cause an error if var is not defined. A safer way would be:

    {% if var is not defined or var is null %}
    

    which can be shortened to:

    {% if var|default is null %}
    

    If you don't provide an argument to the default filter, it assumes NULL (sort of default default). So the shortest and safest way (I know) to check whether a variable is empty (null, false, empty string/array, etc):

    {% if var|default is empty %}
    

提交回复
热议问题