【问题标题】:Symfony 2 : How to render a template outside a controller or in a service?Symfony 2:如何在控制器外部或服务中呈现模板?
【发布时间】:2015-02-23 14:21:58
【问题描述】:

如何在控制器外部或服务中呈现模板?

我一直在关注 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);

所以这里首先缺少的是construct方法的第二个参数:

$helper = new MailHelper($mailer);

但是我将如何实例化 EngineInterface?

当然不可能:

new EngineInterface();

我完全迷路了。

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

【问题讨论】:

标签: symfony


【解决方案1】:

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

【讨论】:

  • 好的,让我再试一次。我确实尝试过使用 Twig_Environment,但我在重置加载程序时遇到了一些问题。我会再试一次并回复你。
  • 我想是因为我试图将其用作服务而不是事件侦听器,所以我必须以这种方式调用服务(如果我使用 \Twig_Environment)。 $helper = new MailHelper($mailer, new \Twig_Environment);它返回:您必须先设置一个加载器。真的有必要吗?
  • 我认为您误解了服务的加载方式。检查 symfony 文档。给你的服务起个名字,比如给它起个名字。通过容器。这样 mailer 和 twig 将自动注入到 Service 构造函数中。
  • 好吧,这更清楚了!非常感谢您的参与。我确实没有以正确的方式调用该服务。 $this->getConfigurationPool()->getContainer()->get('mail_helper');是正确的方式。
  • 我必须如何从控制器传递 $twig?
猜你喜欢
  • 2013-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多