Inject twig variable symfony2

2019-06-28 01:20发布

问题:

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

I think to create a listener and inject it by the listener, could be right?

回答1:

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);
    }


标签: symfony twig