Insert twig variable symfony2
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 to share