交响乐 2 +树枝全局变量
如何让一个树枝全局变量在使用包含更改后保持修改状态?我想要的输出是“设置@更深”,尽管我得到“原始设置”。
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" %}
deep.html.twig
{% set testvar = "set @ deeper" %}
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" %}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自容器感知对象:
From a container aware object :
有趣的问题,我不知道答案,但不管怎样用块和东西玩弄都是行不通的。我查看了生成的 php 缓存模板文件。当您回显变量时,它看起来像:
所以基本上它首先在本地上下文中查找 testvar。如果没有找到,那么它会在全局上下文中查找。
当您设置 test var 的值时,您会得到:
因此只有本地上下文会被更新。当包含的模板返回时,更改的值就会消失。
所以默认情况下,至少看起来全局变量实际上是只读的。
或许可以通过扩展来做到这一点。我对内部的了解还不够。
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:
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:
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.
您是否尝试过通过 Twig 定义全局变量?您可以在 config.yml 文件中执行此操作,如下所示:
因此模板中的
{{my_global_var}}
将打印myvalue
有关详细信息,请阅读 官方文档。
Have you tried to define a global variable through Twig? You can do it in your config.yml file as follows:
So
{{my_global_var}}
in your template will printmyvalue
For more info read the official docs.
可以通过服务定义Twig扩展,请查看此处
It's possible by defining a Twig Extension via Services, check here