Twig Change parent Twig's variable

时间:2015-07-28 15:55:51

标签: symfony twig

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

1 个答案:

答案 0 :(得分:1)

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.