gpt4 book ai didi

Symfony 2 : How to render a template outside a controller or in a service?

转载 作者:行者123 更新时间:2023-12-04 16:23:04 24 4
gpt4 key购买 nike

如何在 Controller 外部或服务中呈现模板?

我一直在关注 Symfony2 的文档。 Doc

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

// ...
}

这就是我调用我的助手的地方:
$transport = \Swift_MailTransport::newInstance();
$mailer = \Swift_Mailer::newInstance($transport);
$helper = new MailHelper($mailer);
$helper->sendEmail($from, $to, $subject, $path_to_twig, $arr_to_twig);

所以这里缺少的第一件事是构造方法的第二个参数:
$helper = new MailHelper($mailer);

但是我将如何实例化EngineInterface?

当然不可能:
new EngineInterface();

我完全迷失在这里。

我需要做的就是为正在发送的电子邮件呈现一个模板。

最佳答案

仅注入(inject) @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
)
);
}
}

关于Symfony 2 : How to render a template outside a controller or in a service?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28675913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com