Inject twig variable symfony2

后端 未结 1 1174
甜味超标
甜味超标 2021-01-19 14:36

I\'m using symfony and I want to inject a variable taken from database. Until now, I inject the variables as below:

twig:
   globals:
       key: value
         


        
1条回答
  •  悲哀的现实
    2021-01-19 14:46

    Yes, you can use a listener to automatically inject dynamic variables into all twig templates. This is exactly what the frameworks does to inject the app object.

    In this example, a project entity is queried and then made available to all twig templates.

    class ProjectEventListener extends ContainerAware implements EventSubscriberInterface
    {
        public function onControllerProject(FilterControllerEvent $event)
        {
            ....
            // Query the project
            $project = $this->getProjectRepository()->findOneBySlug($projectSlug);
    
            // Twig global
            $twig = $this->container->get('twig');
            $twig->addGlobal('project',$project);
        }
    

    0 讨论(0)
提交回复
热议问题