如何在Twig中检查null?

问题描述 投票:0回答:8

我应该使用什么构造来检查 Twig 模板中的值是否为 NULL?

php twig short-circuiting
8个回答
563
投票

取决于您到底需要什么:

  • is null
    检查该值是否为
    null
    :
{% if var is null %}
    {# do something #}
{% endif %}
{% if var is not defined %}
    {# do something #}
{% endif %}

此外,

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

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

140
投票

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

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

或者如果您不希望它在为空时显示:

{{ my_var | default("") }}

39
投票

在没有任何假设的情况下,答案是:

{% if var is null %}

但是,只有当

var
恰好是
NULL
,而不是任何其他计算结果为
false
的值(例如零、空字符串和空数组)时,这才是正确的。另外,如果没有定义
var
,也会导致错误。更安全的方法是:

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

可以缩短为:

{% if var|default is null %}

如果您不向

default
过滤器提供参数,它会假定
NULL
(某种默认值)。因此,检查变量是否为空(null、false、空字符串/数组等)的最短、最安全的方法(我知道):

{% if var|default is empty %}

9
投票

我认为你做不到。这是因为如果变量在树枝模板中未定义(未设置),它看起来像

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
和未定义的var之类的东西也将使该陈述成立。

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


6
投票

您也可以使用一行来完成此操作:

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

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

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

3
投票

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

{% if var is defined %}

var is variable is SET

{% endif %}

0
投票

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

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

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

仅当您的数组

is defined
并且是
NULL

时,这才有效
© www.soinside.com 2019 - 2024. All rights reserved.