![](/img/trans.png)
[英]How to use renderView and twig templating in a Symfony 4 Service
[英]Symfony 3 - Some difficulties to use templating service to send mail
我有一个Mail.php文件,其中包含一些将由我的几个控制器使用的sendMail函数。
我必须使用“模板”服务。 但是我把它放到适当位置时遇到了问题。
我的Services.yml:
email_management:
class: Site\PagesBundle\Utils\Mails
arguments: ['@templating']
public: true
我的Mail.php:
<?php
namespace Site\PagesBundle\Utils;
use Site\PagesBundle\Entity\User;
use Site\PagesBundle\Entity\UserCas;
class Mails
{
private $templating;
public function __construct(EngineInterface $templating)
{
$this->templating = $templating;
}
public function sendMail($user,$raisonMail)
{
$transport = \Swift_SmtpTransport::newInstance();
$mailer = new \Swift_Mailer($transport);
// Entête
$message = \Swift_Message::newInstance()
->setFrom(array('############' => '############'))
//->setTo($user->getEmail());
->setTo("############")
->setCharset('utf-8')
->setContentType('text/html');
switch($raisonMail)
{
case 'formulaireInscription':
dump($user);
// (1) Confirmation de demande d'inscription
$message->setSubject("subject")
->setBody($this->templating->render("@Pages/swiftmail/CreationCompte/DemandeCreationCompte.html.twig",array(
'prenom'=>$user->getPrenom(),
'nom'=>$user->getNom(),
)));
break;
//... other cases
在我的控制器中:
$templating = new EngineInterface;
$mail = new Mail($templating);
$mail->get('email_management')->sendEmail($user,$motif);
但现在我有这个错误:
您必须先设置装载程序。
有人能帮助我吗 ? 谢谢 !
假设打算选择基于服务的选项。 请注意,服务类通常会被移动到项目中的不同文件夹中(位于PagesBundle / Service文件夹下)。
services.yml(请注意更改的路径)
email_management:
class: Site\PagesBundle\Service\EmailManagementService
arguments: ['@templating']
public: true
EmailManagementService.php(请注意更改的位置和命名空间)
<?php
namespace Site\PagesBundle\Service;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Site\PagesBundle\Entity\User;
use Site\PagesBundle\Entity\UserCas;
class Mails
{
private $templating;
public function __construct(EngineInterface $templating)
{
$this->templating = $templating;
}
...
}
控制器中的用法:
$this->get('email_management')->sendMail($user,'formulaireInscription');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.