Symfony 2 + Twig global variables

2019-03-27 06:38发布

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

标签: symfony twig
4条回答
欢心
2楼-- · 2019-03-27 06:44

From a container aware object :

$this->get('twig')->addGlobal('ThomasDecauxIsAwsome', 4);
查看更多
神经病院院长
3楼-- · 2019-03-27 06:52

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

查看更多
Lonely孤独者°
4楼-- · 2019-03-27 06:56

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.

查看更多
Summer. ? 凉城
5楼-- · 2019-03-27 07:08

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.

查看更多
登录 后发表回答