28

I need to render a twig template from a command class in symfony2.

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('[email protected]')
            ->setTo('[email protected]')
            ->setCharset('UTF-8')
            ->setContentType('text/html')       
            ->setBody($this->renderView('mainBundle:Email:default.html.twig'));

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

But when I execute the command php app/console send:emails I get the following error:

Fatal error: Call to undefined method IT\bBundle\Command\CronCommand::renderView()

How can I render the view?

1
  • Just a foot note: if you plan to send bulk emails this is not the way to do it. If it's just once in a while it will be ok. Commented Sep 13, 2012 at 14:21

3 Answers 3

75

It's because renderView is method of class Controller. Instead of that try:

$this->getContainer()->get('templating')->render(...);
Sign up to request clarification or add additional context in comments.

Comments

18

Change

$this->renderView()

to

$this->getContainer()->get('templating')->render()

Comments

9

Maybe, not exactly the question you ask, but for sure - important.

Please, do remember that if you want to send emails via Command call, you need to flushQueue.

$mailer = $container->get('mailer');
$spool = $mailer->getTransport()->getSpool();
$transport = $container->get('swiftmailer.transport.real');
$spool->flushQueue($transport);

1 Comment

Hi, this seems to be not neccessary for all Symfony versions. I use v3.6 and use Commands sending emails without flushing the queue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.