Injecting Twig as a service in Symfony2 Injecting Twig as a service in Symfony2 symfony symfony

Injecting Twig as a service in Symfony2


First of all, lets look at what is available in your service container:

λ php bin/console debug:container | grep twig  twig                                                                 Twig_Environment  ...λ php bin/console debug:container | grep templa  templating                                                           Symfony\Bundle\TwigBundle\TwigEngine  ...

Now we would probably go for TwigEngine class (templating service) instead of Twig_Enviroment (twig service).You can find templating service under vendor\symfony\symfony\src\Symfony\Bundle\TwigBundle\TwigEngine.php

...class TwigEngine extends BaseEngine implements EngineInterface{...

In this class you will find two methods render(..) and renderResponse(...), which means that the rest of your code should work fine with the below example. You will also see that TwigEngine injects twig service (Twig_Enviroment class) to construct it parent class BaseEngine. There fore there is no need to request twig service and your error requesting Twig_Environment should vanish.

So in your code You would do this like so:

# app/config/services.ymlservices:    project.controller.some:        class: Project\SomeBundle\Controller\SomeController        arguments: ['@templating']

Your class

namespace Project\SomeBundle\Controller;use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;use Symfony\Component\HttpFoundation\Response;class SomeController{    private $templating;    public function __construct(EngineInterface $templating)    {        $this->templating = $templating;    }    public function indexAction()    {        return $this->templating->render(            'SomeBundle::template.html.twig',            array(            )        );    }}


  1. Try clearing your cache.

  2. Is your route set up to refer to the controller as a service? If not, Symfony won't utilize the service definition, and therefore any arguments you specify.