10

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.

1
  • Why not set the variable outside of the blocks? It should be usable in both then. Commented Jun 13, 2014 at 19:40

2 Answers 2

16

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 %}

.

5

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

1
  • Link only questions are strongly discouraged. Please add more information in your answer or add the link as a comment.
    – PhoneixS
    Commented Dec 23, 2022 at 9:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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