RenderView in using Symfony Command

How can I use $ this-> renderView inside symfony command (not inside controller)? I'm new to the renderView function, but what do I need to configure to use it with the command?

Thank you in advance for

+7
symfony render
source share
2 answers

Your command class should extend the ContainerAwareCommand class

+17
source share

In Symfony 4, I could not get $this->getContainer()->get('templating')->render($view, $parameters); work.

I have set namespace usage for Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand and the extended ContainerAwareCommand class EmailCommand extends ContainerAwareCommand

I get an exception thrown

 [Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException] You have requested a non-existent service "templating". 

For Symfony 4, this is the solution I came with.

First I installed Twig.

 composer require twig 

Then created his own Twig service.

 <?php # src/Service/Twig.php namespace App\Service; use Symfony\Component\HttpKernel\KernelInterface; class Twig extends \Twig_Environment { public function __construct(KernelInterface $kernel) { $loader = new \Twig_Loader_Filesystem($kernel->getProjectDir()); parent::__construct($loader); } } 

Now my email team is as follows.

 <?php # src/Command/EmailCommand.php namespace App\Command; use Symfony\Component\Console\Command\Command, Symfony\Component\Console\Input\InputInterface, Symfony\Component\Console\Output\OutputInterface, App\Service\Twig; class EmailCommand extends Command { protected static $defaultName = 'mybot:email'; private $mailer, $twig; public function __construct(\Swift_Mailer $mailer, Twig $twig) { $this->mailer = $mailer; $this->twig = $twig; parent::__construct(); } protected function configure() { $this->setDescription('Email bot.'); } protected function execute(InputInterface $input, OutputInterface $output) { $template = $this->twig->load('templates/email.html.twig'); $message = (new \Swift_Message('Hello Email')) ->setFrom(' emailbot@domain.com ') ->setTo(' someone@somewhere.com ') ->setBody( $template->render(['name' => 'Fabien']), 'text/html' ); $this->mailer->send($message); } } 
0
source share

All Articles