如何检查在树枝null?
我应该使用什么构造来检查一个值在NULL模板中是否为NULL?
取决于你需要什么:
- 
is null检查值是否为null:{% if var is null %} {# do something #} {% endif %}
- 
is defined检查variables是否被定义:{% if var is not defined %} {# do something #} {% endif %}
 此外, is sameastesting,这是一个types严格比较两个值,可能会感兴趣检查值以外的null (如false ): 
 {% if var is sameas(false) %} {# do something %} {% endif %} 
如何在树枝中设置默认值: http : //twig.sensiolabs.org/doc/filters/default.html
 {{ my_var | default("my_var doesn't exist") }} 
或者如果你不希望它显示null:
 {{ my_var | default("") }} 
没有任何假设,答案是:
 {% if var is null %} 
 但是,只有当var完全为NULL ,而不是任何其他值为false值(例如零,空string和空数组)时,才会成立。 另外,如果var没有定义,会导致错误。 更安全的方法是: 
 {% if var is not defined or var is null %} 
可以缩短为:
 {% if var|default is null %} 
 如果您没有为defaultfilter提供参数,则它将采用NULL (默认为默认)。 所以最短和最安全的方法(我知道)来检查一个variables是否为空(空,假,空string/数组等): 
 {% if var|default is empty %} 
 我不认为你可以。 这是因为如果一个variables在树枝模板中是未定义的(没有设置),它看起来像NULL或none (以树枝的forms)。 我敢肯定,这是为了抑制在模板中发生错误的访问错误。 
 由于树枝( === )中缺less“身份”,这是最好的select 
 {% if var == null %} stuff in here {% endif %} 
其转化为:
 if ((isset($context['somethingnull']) ? $context['somethingnull'] : null) == null) { echo "stuff in here"; } 
 如果你擅长你的types杂耍 ,意味着诸如0 , '' , FALSE , NULL和一个未定义的var之类的东西也会使这个陈述成为现实。 
我的build议是要求在Twig中实施身份。
  //test if varibale exist {% if var is defined %} //todo {% endif %} //test if variable is not null {% if var is not null %} //todo {% endif %} 
你可以使用下面的代码来检查是否
 {% if var is defined %} var is variable is SET {% endif %} 
你也可以用一行来做到这一点:
 {{ yourVariable is not defined ? "Not Assigned" : "Assigned" }}