如何在EventListener中呈现模板?

时间:2011-07-29 14:16:53

标签: symfony

如何在Symfony 2中的EventListener中渲染模板?

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);
    }
}

你可以帮帮我吗?

2 个答案:

答案 0 :(得分:59)

当您在控制器中呼叫$this->render()时,它实际上只是$this->container->get('templating')->renderResponse()的快捷方式。如果将@templating作为构造函数参数传递给配置文件中的EventListener,则可以使用模板引擎执行任何操作。

作为参考,如果您想查看模板引擎的代码,命令./app/console container:debug表示templatingSymfony\Bundle\TwigBundle\TwigEngine的实例。

答案 1 :(得分:0)

您可以像下面那样注入EngineInterface;

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('test@test.com')
            ->setTo('user@user.com')
            ->setBody($this->_engine->render('mails/test.html.twig',[
             ])
        );