Hazarapet Tunanyan
Hazarapet Tunanyan

Reputation: 2865

Twig Change parent Twig's variable

I have 2 Twigs: Twig1, Twig2. I included Twig2 in Twig1.

In Twig1 I have declared variable foo. How can I change Twig1 foo variable from Twig2 by 'reference'?

// Twig1
{% set a = 5 %}
{{ include(Twig2) }}
{{ a }} //expected 50 got 5

Twig2

// Twig2
{% set a = 50 %}

Upvotes: 1

Views: 1580

Answers (1)

Jovan Perovic
Jovan Perovic

Reputation: 20193

As per Twig official docs:

Included templates have access to the variables of the active context.

So, just do:

{% set foo = "something else" %}

Hope I understood what you meant...

Edit:

I think that's one of differences between {% include %} and {{ include }}. If I'm right, the first one has direct access to context, while the second one gets the context passed to it. So, depending on what you really want to accomplish, you could do:

// Twig1
{% set a = 5 %}
{% include "Twig2" %}
{{ a }} //expected 50 got 5

// Twig2
{% set a = 50 %}

Does this work?

Edit 2:

Seems it's not possible after all. Extensive explanation here.

Upvotes: 1

Related Questions