如何在控制器或服务外部渲染模板?
我一直在关注Symfony2的文档.文件
namespace Acme\HelloBundle\Newsletter;
use Symfony\Component\Templating\EngineInterface;
class NewsletterManager
{
protected $mailer;
protected $templating;
public function __construct(
\Swift_Mailer $mailer,
EngineInterface $templating
) {
$this->mailer = $mailer;
$this->templating = $templating;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
这就是我打电话给我的帮手:
$transport = \Swift_MailTransport::newInstance();
$mailer = \Swift_Mailer::newInstance($transport);
$helper = new MailHelper($mailer);
$helper->sendEmail($from, $to, $subject, $path_to_twig, $arr_to_twig);
Run Code Online (Sandbox Code Playgroud)
所以这里缺少的第一件事是构造方法的第二个参数:
$helper = new MailHelper($mailer);
Run Code Online (Sandbox Code Playgroud)
但是我如何实例化EngineInterface?
当然不能是:
new EngineInterface();
Run Code Online (Sandbox Code Playgroud)
我完全迷失在这里.
我需要做的就是为正在发送的电子邮件呈现模板.
web*_*ers 22
仅注入@twig并将呈现的模板传递给邮件程序正文:
<?php
namespace Acme\Bundle\ContractBundle\Event;
use Acme\Bundle\ContractBundle\Event\ContractEvent;
class ContractListener
{
protected $twig;
protected $mailer;
public function __construct(\Twig_Environment $twig, \Swift_Mailer $mailer)
{
$this->twig = $twig;
$this->mailer = $mailer;
}
public function onContractCreated(ContractEvent $event)
{
$contract = $event->getContract();
$body = $this->renderTemplate($contract);
$projectManager = $contract->getProjectManager();
$message = \Swift_Message::newInstance()
->setSubject('Contract ' . $contract->getId() . ' created')
->setFrom('noreply@example.com')
->setTo('dev@example.com')
->setBody($body)
;
$this->mailer->send($message);
}
public function renderTemplate($contract)
{
return $this->twig->render(
'AcmeContractBundle:Contract:mailer.html.twig',
array(
'contract' => $contract
)
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13803 次 |
| 最近记录: |