In my symfony2 application, I have a getPorfolioUser method which return a specific user variable.
I am looking forward to be able to call
{%
One approach is use a CONTROLLER event listener. I like to use CONTROLLER instead of REQUEST because it ensures that all the regular request listeners have done their thing already.
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProjectEventListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array
(
KernelEvents::CONTROLLER => array(
array('onControllerProject'),
),
);
}
private $twig;
public function __construct($twig)
{
$this->twig = $twig;
}
public function onControllerProject(FilterControllerEvent $event)
{
// Generate your data
$project = ...;
// Twig global
$this->twig->addGlobal('project',$project);
}
# services.yml
cerad_project__project_event_listener:
class: ...\ProjectEventListener
tags:
- { name: kernel.event_subscriber }
arguments:
- '@twig'
Listeners are documented here: http://symfony.com/doc/current/cookbook/service_container/event_listener.html
Another approach would be to avoid the twig global altogether and just make a twig extension call. http://symfony.com/doc/current/cookbook/templating/twig_extension.html
Either way works well.