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


当前回答

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

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

其他回答

你也可以用一行来做到这一点:

{{ yourVariable is not defined ? "Not Assigned" : "Assigned" }}

此外,如果你的变量是一个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 defined %}

var is variable is SET

{% endif %}

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

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

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

{{ my_var | default("") }}
     //test if varibale exist
     {% if var is defined %}
         //todo
     {% endif %}

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