defined

defined 检查变量是否在当前上下文中定义。如果您使用 strict_variables 选项:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
{# defined works with variable names #}
{% if foo is defined %}
    ...
{% endif %}

{# and attributes on variables names #}
{% if foo.bar is defined %}
    ...
{% endif %}

{% if foo['bar'] is defined %}
    ...
{% endif %}

当使用 defined 测试在某些方法调用中使用变量的表达式,请确保首先定义了所有变量:

1
2
3
{% if var is defined and foo.method(var) is defined %}
    ...
{% endif %}