[英]How to pass object to the layout view without action in Symfony 2?
I would like to create in layout dynamic menu, which will be manage from administrative panel. 我想在布局动态菜单中创建,将通过管理面板进行管理。 What i know is the object can be pass to view by the action from controller.
我所知道的是对象可以通过控制器的动作传递给查看。
What i want is pass object to layout ( twig engine ) without using controller and that will work independently form controller and action. 我想要的是不使用控制器将对象传递到布局(树枝引擎),并且可以独立于控制器和动作工作。
How can i do that? 我怎样才能做到这一点?
If you want a global variable / object in Twig, you have to implement Twig_Extension
and add a new global (which will be accessible to all your templates). 如果要在Twig中使用全局变量/对象,则必须实现
Twig_Extension
并添加一个新的全局变量(所有模板均可访问)。
A simple example would be: 一个简单的例子是:
1) Register a service in <bundle>/Resources/config/services.yml
1)在
<bundle>/Resources/config/services.yml
注册服务
services:
acme.twig.acme_extension:
class: Acme\DemoBundle\Twig\AcmeExtension
tags:
- { name: twig.extension }
2) Then create the extension: 2)然后创建扩展名:
<?php
namespace Acme\DemoBundle\Twig
class AcmeExtension extends \Twig_Extension {
public function getGlobals() {
return [
'menu' => new Menu(),
];
}
}
3) Then in your template: 3)然后在您的模板中:
{{ menu.render }} // Whatever
Of course, you can pass arguments to the Twig extension if needed. 当然,如果需要,您可以将参数传递给Twig扩展。
Anyway, if you're trying to build a menu, maybe you should have a look at KnpMenuBundle, which helps a lot ( https://github.com/KnpLabs/KnpMenuBundle ) 无论如何,如果您要构建菜单,也许您应该看看KnpMenuBundle,这会很有帮助( https://github.com/KnpLabs/KnpMenuBundle )
Hope it helps! 希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.