Symfony 2:如何在控制器外部或服务中呈现模板? [英] Symfony 2 : How to render a template outside a controller or in a service?

查看:22
本文介绍了Symfony 2:如何在控制器外部或服务中呈现模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在控制器外部或服务中渲染模板?

How to render a template outside a controller or in a service?

我一直在关注 Symfony2 的文档.文档

I've been following the documentation of 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;
    }

    // ...
}

这是我打电话给我的帮手的地方:

This is where i call my helper :

$transport = \Swift_MailTransport::newInstance();
$mailer = \Swift_Mailer::newInstance($transport);
$helper = new MailHelper($mailer);
$helper->sendEmail($from, $to, $subject, $path_to_twig, $arr_to_twig);

所以这里缺少的第一件事是构造方法的第二个参数:

So the first thing here missing is the second parameter of the construct method in :

$helper = new MailHelper($mailer);

但是我将如何实例化 EngineInterface?

But how would i instantiate the EngineInterface?

当然不可能:

new EngineInterface();

我完全迷失在这里.

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

All what i need to do is render a template for the email that is being sent.

推荐答案

只注入 @twig 并将渲染的模板传递给邮件程序主体:

Inject only @twig and pass the rendered template to the mailer body:

<?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:如何在控制器外部或服务中呈现模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆