另外,如何检查是否在 Twig 模板中定义了 var

How to check, also, if var is defined at Twig template

我在 Twig 模板中有这段代码:

{% if form_action is empty or form_action is null or form_action is not defined %}
    {% set form_action = '' %}
{% endif %}

但是当我加载页面时,我收到了这条错误消息:

Variable "form_action" does not exist in AppBundle::pdone.html.twig at line 1

如何检查是否设置了变量?条件还不够吗?有什么建议吗?

使用is defined

{% if form_action is defined %}
 {# Do your stuff here #}
{% endif %}

你的语句顺序不正确。通常这应该足够了:

{% if form_action is not defined %}

查看variable是否有值:

{% if form_action %}