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.
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
)
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With