How can I render a template inside an EventListener in Symfony 2?
class RequestListener
{
public function __construct() { }
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
// Here I want to render a particular twig template
$response = new Response('Forbidden', 401);
// replacing the response...
$event->setResponse($response);
}
}
Could you help me with that?
When you call
$this->render()in a Controller, it’s really just a shortcut for$this->container->get('templating')->renderResponse(). If you pass@templatingas a constructor argument to your EventListener in your configuration file, you’ll be able to do whatever you’d like with the templating engine.For reference, if you’d like to look at the code of the templating engine, the command
./app/console container:debugsays thattemplatingis an instance ofSymfony\Bundle\TwigBundle\TwigEngine.