How to render a template inside an EventListener?

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',[
             ])
        );

Tags:

Symfony