How to get Request object inside a Twig Extension in Symfony?

symfony, twig

Solution

Register your extension as a service and give it the container service:

# services.yml

services:

    sybio.twig_extension:
        class: %sybio.twig_extension.class%
        arguments: 
            - @service_container
        tags:
            - { name: twig.extension, priority: 255 }

Then retrieve the container by your (twig extension) class constructor and then the request:

<?php 
    // Your class file:

    // ...

    class MyClass extends \Twig_Extension
    {
        /**
         * @var ContainerInterface
         */
        protected $container;

        /**
         * @var Request
         */
        protected $request;

        /**
         * Constructor
         * 
         * @param ContainerInterface $container
         */
        public function __construct($container)
        {
            $this->container = $container;

            if ($this->container->isScopeActive('request')) {
                $this->request = $this->container->get('request');
            }
        }

        // ...

Note that testing the scope is usefull because there is no request when running console command, it avoids warnings.

That's it, you are able to use the request !

Problem

How can one access the `Request` object inside Twig Extension? ``` namespace Acme\Bundle\Twig; use Twig_SimpleFunction; class MyClass extends \Twig_Extension { public function getFunctions() { return array( new Twig_SimpleFunction('xyz', function($param) { /// here $request = $this->getRequestObject(); }) ); } public function getName() { return "xyz"; } } ```

Original source