28

symfony2 のコマンド クラスから twig テンプレートをレンダリングする必要があります。

namespace IT\bBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class CronCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('send:emails')
            ->setDescription('Envio programado de emails');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $message = \Swift_Message::newInstance()
            ->setSubject('bla bla')
            ->setFrom('x@x.com')
            ->setTo('x@gmail.com')
            ->setCharset('UTF-8')
            ->setContentType('text/html')       
            ->setBody($this->renderView('mainBundle:Email:default.html.twig'));

        $this->getContainer()->get('mailer')->send($message);
        $output->writeln('Enviado!');
    }
}

しかし、コマンドを実行するとphp app/console send:emails、次のエラーが発生します。

致命的なエラー: 未定義のメソッドの呼び出しIT\bBundle\Command\CronCommand::renderView()

ビューをレンダリングするにはどうすればよいですか?

4

3 に答える 3

75

renderView が Controller クラスのメソッドだからです。その代わりに:

$this->getContainer()->get('templating')->render(...);
于 2012-09-13T14:14:02.893 に答える
18

変化する

$this->renderView()

$this->getContainer()->get('templating')->render()
于 2012-09-13T14:13:21.777 に答える
9

おそらく、あなたが尋ねる質問とは正確には異なりますが、確かに-重要です。

コマンド呼び出しを介してメールを送信する場合は、flushQueue が必要であることを覚えておいてください。

$mailer = $container->get('mailer');
$spool = $mailer->getTransport()->getSpool();
$transport = $container->get('swiftmailer.transport.real');
$spool->flushQueue($transport);
于 2015-09-15T21:48:19.997 に答える