How to inject the request stack into a twig extension

php, request, symfony

Solution

When constructing the twig extension, there are no requests in the stack yet, it is empty.

You should delay retrieving the request from the stack to the renderPaginator() method.

Service definition:

app.twig_extension:
    class: MyBundle\Twig\MyExtension
    public: false
    arguments: [@request_stack, @router]
    tags:
        - { name: twig.extension }

Service:

public function __construct(RequestStackInterface $requestStack, RouterInterface $router)
{
    $this->requestStack = $requestStack;
    $this->router = $router;
}

public function renderPaginator(\Twig_Environment $twig, $paginator, array $options = array())
{

    if ( 1 == $paginator->getNumPages() )
    {
        return false;
    }
    var_dump($this->requestStack->getCurrentRequest());
    die();
}

Problem

I'm trying to create an extension to render a pagination. It needs the request and the router to be able to create the URL's, so I did this: services.yml: ``` app.twig_extension: class: MyBundle\Twig\MyExtension public: false calls: - [setRequest, [@request_stack]] - [setRouter, [@router]] tags: - { name: twig.extension } ``` Then in my extension: ``` private $router; private $request; public function setRouter( UrlGeneratorInterface $router ) { $this->router = $router; } public function setRequest(RequestStack $requestStack) { $this->request = $requestStack->getCurrentRequest(); } ``` ... ``` public function renderPaginator(\Twig_Environment $twig, $paginator, array $options = array()) { if ( 1 == $paginator->getNumPages() ) { return false; } var_dump($this->request); die(); ``` Turns out that the var_dump prints null. Although if I do that var_dump in the setRequest method it actually prints a Request object. Any idea? Thanks!

Original source