Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render a template inside an EventListener?

Tags:

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?

like image 518
dmirkitanov Avatar asked Jul 29 '11 14:07

dmirkitanov


2 Answers

When you call $this->render() in a Controller, it's really just a shortcut for $this->container->get('templating')->renderResponse(). If you pass @templating as 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:debug says that templating is an instance of Symfony\Bundle\TwigBundle\TwigEngine.

like image 186
Derek Stobbe Avatar answered Sep 19 '22 13:09

Derek Stobbe


You may inject EngineInterface like following;

use Twig\Environment;  public $_engine;  public function __construct(\Swift_Mailer $mailer, Environment $engine) {     $this->mailer= $mailer;     $this->_engine = $engine; }  this->mailer->send( (new \Swift_Message('something happened'))             ->setFrom('[email protected]')             ->setTo('[email protected]')             ->setBody($this->_engine->render('mails/test.html.twig',[              ])         ); 
like image 45
Tuncay Elvanağaç Avatar answered Sep 22 '22 13:09

Tuncay Elvanağaç