Insert twig variable symfony2

I am using symfony and I want to inject a variable taken from the database. So far, I am inserting variables as shown below:

twig:
   globals:
       key: value

      

I am thinking to create a listener and inject it with a listener maybe correct?

+3


source to share


1 answer


Yes, you can use a listener to automatically add dynamic variables to all branch templates. This is exactly what frameworks do for the application of the application object.

In this example, a project object is requested and then made available to all templates in the branch.



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

      

+3


source







All Articles