Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 + Twig global variables

Tags:

twig

symfony

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" %}
like image 471
ojreadmore Avatar asked Feb 13 '12 16:02

ojreadmore


3 Answers

From a container aware object :

$this->get('twig')->addGlobal('ThomasDecauxIsAwsome', 4);
like image 146
Thomas Decaux Avatar answered Oct 05 '22 05:10

Thomas Decaux


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.

like image 39
Cerad Avatar answered Oct 05 '22 03:10

Cerad


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.

like image 42
JeanValjean Avatar answered Oct 05 '22 04:10

JeanValjean