Symfony2: Как использовать twig шаблоны в service container?

Необходимо отправлять данные формы (название поля + значение) на email. Но не могу разобраться как подключить шаблоны твиг в сервисе.
Ошибка:
Attempted to call an undefined method named "render" of class "AppBundle\Helper\Notification".

//  SomeController.php
...
if ($form->isSubmitted()) {
   if ($form->isValid()) {
      $this->get('app.send.notification') 
           ->send('Заголовок', $form);
   }
}

// services.yml
services:
    app.send.notification:
        class: AppBundle\Helper\Notification
        arguments:
          service: ["@service_container"]

<?php
// AppBundle\Helper\Notification
namespace AppBundle\Helper;

use Symfony\Component\DependencyInjection\ContainerInterface as Container;

class Notification {
    
/**
 * admin email address
 */
const EMAIL_FROM = 'admin@examle.com';
   
/**
 * my email address
 */
const EMAIL_TO = 'my@example.ru';
  
/*
 * @var array
 */
protected $dataMail = [];


/**
 * service container
 *
 * @var object
 */
protected $service;
 
/**
 * init service
 *
 * @param object $service
 * @return $this
 */
public function __construct($service) {
    $this->service = $service;
    return $this;
}

/**
 * Send notification
 *
 * @param string $subject
 * @param array $form
 */    
public function send($subject, $form) {
        
    $data_form = $form->all();
    array_pop($data_form);

    foreach ($data_form as $value) {
        $label = $value->getConfig()
                       ->getOption("label");
        $data = $value->getData();
        $res = ($data instanceof \DateTime) ? ($data->format('d.m.Y')) : $data;
        $this->dataMail[$label] = $res;

        try {
            $message = \Swift_Message::newInstance()
                    ->setSubject($subject)
                    ->setFrom(self::EMAIL_FROM)
                    ->setTo(self::EMAIL_TO)
                    ->setBody(
                        $this->render(
                            'Emails/request.html.twig', array('form' => $dataMail)
                        ), 'text/plain');
            
            $this->service->get('mailer')->send($message);
        } catch (Swift_TransportException $e) {
            return $e->getMessage();
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }
}

// request.html.twig
{% for value in form %}
    {{ value }}
{% endfor %}
  • Вопрос задан
  • 1089 просмотров
Решения вопроса 1
@dizzy7
Вам необходимо передать в сервис шаблонизатор, т.е.
app.send.notification:
        class: AppBundle\Helper\Notification
        arguments:
          service: ["@templating"]

В сервисе:
public function __construct($templating) { //Класс по-моему Twig_Engine, могу ошибаться
    $this->templating = $templating;
}

И использовать его соответственно как:
$this->templating->render(...);
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@jaxel
$this->container->get('templating')->renderView($view, $parameters)
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы