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 @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
.
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',[ ]) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With