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


我认为你做不到。这是因为如果一个变量在树枝模板中未定义(未设置),它看起来像NULL或none(在树枝术语中)。我很确定这是为了防止在模板中发生糟糕的访问错误。

由于在《Twig》中缺少“身份”(===),这是你所能做的最好的事情

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

翻译过来就是:

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

如果你擅长你的类型杂耍,这意味着像0,“,FALSE, NULL,和一个未定义的变量也会使该声明为真。

我的建议是要求将身份实现到Twig中。

具体取决于你需要什么:

Is null检查值是否为空: {%如果var为空%} {#做某事#} {% endif %} Is defined检查变量是否已定义: {%如果var没有定义%} {#做某事#} {% endif %}

此外,is sameas测试对两个值进行严格的类型比较,对于检查null以外的值(如false)可能会感兴趣:

{% if var is sameas(false) %}
    {# do something %}
{% endif %}

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

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

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

{{ my_var | default("") }}

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

{% if var is defined %}

var is variable is SET

{% endif %}

不做任何假设,答案是:

{% 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 %}
     //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的情况下起作用