用于在 symfony 4 中生成树枝模板的命令控制台



我一直在重读symfony 4文档,尝试使用控制台命令生成twig模板,但我没有找到命令。有没有人知道使用控制台命令生成树枝模板的捆绑包?

我解决了

 class SendEmailNotify extends Command
{
    private $container;
    private $twig;
    private $mailer;
    public function __construct($name = null, PsrContainerContainerInterface $container, Swift_Mailer $mailer)
    {
        parent::__construct($name);
        $this->container = $container;
        $this->twig = $this->container->get('twig');
        $this->mailer = $mailer;
    }

我检查了一下,可悲的答案是否定的。此处提供了制作者命令列表。您甚至可以制作树枝扩展,但不能制作视图。我认为值得提交给他们。

我需要 Twig 功能来从我的自定义控制台命令发送电子邮件。

这就是我想出的解决方案。

首先,我安装了Twig。

composer require "twig/twig:^2.0"

然后创建了我自己的树枝服务。

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

现在我的电子邮件命令看起来像这样。

<?php
# src/Command/EmailCommand.php
namespace AppCommand;
use SymfonyComponentConsoleCommandCommand,
    SymfonyComponentConsoleInputInputInterface,
    SymfonyComponentConsoleOutputOutputInterface,
    AppServiceTwig;
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);
    }
}

此指令将创建一个没有树枝模板的控制器

php bin/console make:controller --no-template  

令人惊讶的是,此指令将创建一个控制器和一个模板文件和子目录

php bin/console make:controller 

最新更新