我应该使用什么结构来检查一个值是否为NULL在树枝模板?


当前回答

此外,如果你的变量是一个ARRAY,也有几个选项:

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

OR

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

这只会在你的数组被定义并且为NULL的情况下起作用

其他回答

不做任何假设,答案是:

{% if var is null %}

但只有当var完全为NULL,而不是任何其他值为false(如零,空字符串和空数组)时,这才为真。此外,如果没有定义var,则会导致错误。更安全的方法是:

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

可以缩写为:

{% if var|default is null %}

如果不为默认过滤器提供参数,则默认为NULL(类似于默认的default)。所以(我知道)检查变量是否为空(null, false,空字符串/数组等)的最短和最安全的方法:

{% if var|default is empty %}

您可以使用下面的代码检查是否

{% if var is defined %}

var is variable is SET

{% endif %}

此外,如果你的变量是一个ARRAY,也有几个选项:

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

OR

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

这只会在你的数组被定义并且为NULL的情况下起作用

     //test if varibale exist
     {% if var is defined %}
         //todo
     {% endif %}

     //test if variable is not null
     {% if var is not null %}
         //todo
     {% endif %}

如何设置默认值在twig: http://twig.sensiolabs.org/doc/filters/default.html

{{ my_var | default("my_var doesn't exist") }}

或者如果你不希望它显示为空:

{{ my_var | default("") }}