8

Something that would work like this:

{% block A %}
  {% set testVar = "foo" %}
{% endblock %}
...
{% block B %}
  {{ testVar }}
{% endblock %}

The scope of testVar seems limited to {% block A %}

I'm looking for a way around this, so that the child template can pass content to the parent to use in other blocks.

This is an issue since the child template that extends the parent cannot have content outside a defined block.

  • Why not set the variable outside of the blocks? It should be usable in both then. – Bryan Redeagle Jun 13 '14 at 19:40
13

Twig variables are only accessible inside their own scope.

.

What is a scope:

Tags like {% block %}, {% for %}, {% nav %} create a 'scope', which means that variables defined inside them, can't be accessed from outside. This is similar to local variables inside php-functions:

{% block A %}
    {% set var = 'apple' %}
    {{ var }} {# This prints apple #}
{% endblock %}

{% block B %}
    {{ var }} {# This doesn't prints anything, since var isn't defined #}
{% endblock %}

.

Variables outside their scope:

To make variables accessible outside their scope you have to define them before:

{% set var = 'apple' %}  

{% block A %}
    {{ var }} {# This prints apple #}
{% endblock %}

{% block B %}
    {% set var = 'banana' %}
    {{ var }} {# This prints banana #}
{% endblock %}

{% block A %}
    {{ var }} {# This prints banana #}
{% endblock %}

.

3

This article may help as well: Twig Processing Order & Scope

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.