In my symfony2 application, I have a getPorfolioUser method which return a specific user variable.
I am looking forward to be able to call
{% if portfolio_user %}
in twig. I did not understand how I could set this as a global variable as from the documentation I am under the impression I can only set fixed elements or services but not services' methods.
Am I obliged to write an extension or a helper for that ? What the simpler way of doing this ?
Thanks!
If you are using Twig in another project, you can set your globals directly in the environment: $twig = new Twig_Environment($loader); $twig->addGlobal('myStuff', $someVariable); And then use {{ myStuff }} anywhere in your application.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With