Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig runs in 'if variable is defined', even when variable is defined

Tags:

twig

I want to include a template, when a variable is set. When the variable isn't set, the template must not be included.

{% if data is defined %}
    {% block content %}
        {% include 'data.html.twig' with  { 'data' : data} %} {# Line 14 #}
    {% endblock %}  
{% endif %}

But this check doesn't work. When data isn't defined an error occures:

 Twig_Error_Runtime: Variable "data" does not exist in "text.html.twig" at line 14

But Twig has to skip that line when data is defined. Who can explain this behaviour, en more importan: How can I solve this?

like image 383
OrangeTux Avatar asked Dec 18 '12 20:12

OrangeTux


1 Answers

Thanks to my roommate, I found the solution. The if has to be in the block. I still don't know why this is required.

 {% block content %}
    {% if data is defined %}
        {% include 'data.html.twig' with  { 'data' : data} %} {# Line 14 #}
   {% endif %}
{% endblock %}
like image 168
OrangeTux Avatar answered Sep 24 '22 21:09

OrangeTux