service method as twig global variable

前端 未结 4 479
有刺的猬
有刺的猬 2020-12-19 01:52

In my symfony2 application, I have a getPorfolioUser method which return a specific user variable.

I am looking forward to be able to call

{%

4条回答
  •  一个人的身影
    2020-12-19 02:31

    One approach is use a CONTROLLER event listener. I like to use CONTROLLER instead of REQUEST because it ensures that all the regular request listeners have done their thing already.

    use Symfony\Component\HttpKernel\KernelEvents;
    use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
    
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class ProjectEventListener implements EventSubscriberInterface
    {
    public static function getSubscribedEvents()
    {
        return array
        (
            KernelEvents::CONTROLLER => array(
                array('onControllerProject'),
            ),
        );
    }
    private $twig;
    public function __construct($twig)
    {
        $this->twig = $twig;
    }
    public function onControllerProject(FilterControllerEvent $event)
    {
        // Generate your data
        $project = ...;
    
        // Twig global
        $this->twig->addGlobal('project',$project);    
    }
    
    # services.yml
    cerad_project__project_event_listener:
        class: ...\ProjectEventListener
        tags:
            - { name: kernel.event_subscriber }
        arguments:
            - '@twig'
    

    Listeners are documented here: http://symfony.com/doc/current/cookbook/service_container/event_listener.html

    Another approach would be to avoid the twig global altogether and just make a twig extension call. http://symfony.com/doc/current/cookbook/templating/twig_extension.html

    Either way works well.

提交回复
热议问题