Symfony 2 + Twig 全局变量 [英] Symfony 2 + Twig global variables

查看:32
本文介绍了Symfony 2 + Twig 全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个twig全局变量在使用includes改变后如何保持修改?虽然我得到了原始设置",但我想要的输出是设置@更深".

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

app/config/config.yml

twig:
    globals:
      testvar: "original setting"

root.html.twig

root.html.twig

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

levelone.html.twig

levelone.html.twig

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

deeper.html.twig

deeper.html.twig

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

推荐答案

有趣的问题,我不知道答案,但不管用块什么的东西都不会奏效.我查看了生成的 php 缓存模板文件.当你回显一个变量时,它看起来像:

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);

所以基本上它首先在您的本地上下文中查找 testvar.如果未找到,则在全局上下文中查找.

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

当您设置 test var 的值时,您会得到:

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.

这篇关于Symfony 2 + Twig 全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆