Symfony 2 + Twig global variables

2019-03-27 06:45发布

问题:

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

回答1:

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.



回答2:

From a container aware object :

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


回答3:

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.



回答4:

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



标签: symfony twig