ojreadmore
ojreadmore

Reputation: 1475

Symfony 2 + Twig global variables

How can one get a twig global variable to maintain modification after changing it with includes? My desired output is "set @ deeper" though I get "original setting".

app/config/config.yml

twig:
    globals:
      testvar: "original setting"

root.html.twig

{% include "MyBundle::levelone.html.twig" %}
{{ testvar }}

levelone.html.twig

{% set testvar = "set @ levelone" %}
{% include "MyBundle::deeper.html.twig" %}

deeper.html.twig

{% set testvar = "set @ deeper" %}

Upvotes: 8

Views: 19955

Answers (4)

Cerad
Cerad

Reputation: 48865

Interesting question and I don't know an answer but no amount fooling around with blocks and stuff will work. I looked in the generated php cache template files. When you echo a variable it looks like:

// {{ testvar }}
echo twig_escape_filter($this->env, $this->getContext($context, "testvar"), "html", null, true);

So basically it first looks for testvar in your local context. If not found then it looks in the global context.

When you set the value of test var you get:

// {% set testvar = 'level one' }}
$context["testvar"] = "level one";

So only the local context gets updated. The changed value goes away when the included template returns.

So by default at least it looks like global variables are really read only.

It might be possible to do this through an extension. I don't know enough about the internals.

Upvotes: 6

Thomas Decaux
Thomas Decaux

Reputation: 22651

From a container aware object :

$this->get('twig')->addGlobal('ThomasDecauxIsAwsome', 4);

Upvotes: 8

sepehr
sepehr

Reputation: 5729

It's possible by defining a Twig Extension via Services, check here

Upvotes: 0

JeanValjean
JeanValjean

Reputation: 17713

Have you tried to define a global variable through Twig? You can do it in your config.yml file as follows:

twig:
    globals:
        my_global_var : myvalue

So {{my_global_var}} in your template will print myvalue

For more info read the official docs.

Upvotes: 1

Related Questions