即使定义了变量,Twig也会在'if variable is defined'中运行

Ora*_*Tux 5 twig

我想在设置变量时包含模板.如果未设置变量,则不得包含模板.

{% if data is defined %}
    {% block content %}
        {% include 'data.html.twig' with  { 'data' : data} %} {# Line 14 #}
    {% endblock %}  
{% endif %}
Run Code Online (Sandbox Code Playgroud)

但是这个检查不起作用.当data没有定义一个错误occures:

 Twig_Error_Runtime: Variable "data" does not exist in "text.html.twig" at line 14
Run Code Online (Sandbox Code Playgroud)

data定义后,Twig必须跳过该行.谁可以解释这种行为,更重要的是:我该如何解决这个问题?

Ora*_*Tux 11

感谢我的室友,我找到了解决方案.本if必须是在block.我仍然不知道为什么这是必需的.

 {% block content %}
    {% if data is defined %}
        {% include 'data.html.twig' with  { 'data' : data} %} {# Line 14 #}
   {% endif %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)