Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

symfony

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

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

But how would i instantiate the EngineInterface?

Of course it can't be :

new EngineInterface();

I'm totally lost here.

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

like image 896
Brieuc Avatar asked Feb 23 '15 14:02

Brieuc


1 Answers

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('[email protected]')
            ->setTo('[email protected]')
            ->setBody($body)
        ;
        $this->mailer->send($message);
    }

    public function renderTemplate($contract)
    {
        return $this->twig->render(
            'AcmeContractBundle:Contract:mailer.html.twig',
            array(
                'contract' => $contract
            )
        );
    }
}
like image 90
webDEVILopers Avatar answered Nov 23 '22 17:11

webDEVILopers