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