Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

service method as twig global variable

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!

like image 582
Sébastien Avatar asked Mar 04 '15 19:03

Sébastien


People also ask

How do I add a global variable in twig?

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.


1 Answers

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.

like image 118
Cerad Avatar answered Sep 30 '22 18:09

Cerad