I keep rereading the symfony 4 documentation to try to generate twig template with the console commands but I did not find a command . Is there any one know a bundle to generate twig template with console commands ?
4 Answers
I'm solved
class SendEmailNotify extends Command
{
private $container;
private $twig;
private $mailer;
public function __construct($name = null, \Psr\Container\ContainerInterface $container, \Swift_Mailer $mailer)
{
parent::__construct($name);
$this->container = $container;
$this->twig = $this->container->get('twig');
$this->mailer = $mailer;
}
Comments
I checked it and the sad answer is no. The list of maker commands is available here. You can even make a twig extension, but not a view. It is worth submitting to them I think.
2 Comments
user7430779
can you explain me what is the twig extension exactly ?
Michał Skrzypek
Sure, it is an additional filter or function for twig, like for instance {{ variable | length }} (the lenght part). So sadly nothing that would help in your case.
I needed Twig functionality to send emails from my custom console command.
This is the solution I came up with.
First I installed Twig.
composer require "twig/twig:^2.0"
Then created my 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 command looks like this.
<?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('[email protected]')
->setTo('[email protected]')
->setBody(
$template->render(['name' => 'Fabien']),
'text/html'
);
$this->mailer->send($message);
}
}
template.html.twig? (it's not a troll, i'm really curious)