duanji2002 2014-11-30 10:02
浏览 32
已采纳

如何在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?

  • 写回答

1条回答 默认 最新

  • dpo69086 2014-11-30 11:21
    关注

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

    A simple example would be:

    1) Register a service in <bundle>/Resources/config/services.yml

    services:
      acme.twig.acme_extension:
        class: Acme\DemoBundle\Twig\AcmeExtension
        tags:
          - { name: twig.extension }
    

    2) Then create the extension:

    <?php
    
    namespace Acme\DemoBundle\Twig
    
    class AcmeExtension extends \Twig_Extension {
      public function getGlobals() {
        return [
          'menu' => new Menu(),
        ];
      }
    }
    

    3) Then in your template:

    {{ menu.render }} // Whatever
    

    Of course, you can pass arguments to the Twig extension if needed.

    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)

    Hope it helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效