RenderView in Symfony Command usage

后端 未结 3 2214
迷失自我
迷失自我 2021-02-20 08:52

How can I use $this->renderView inside a symfony Command (not inside a controller)? I new about the function \"renderView\" but what do I have to setup to use it wihtin a comman

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-20 09:17

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

    I set the namespace use for Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand and 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 up with.

    First I installed Twig.

    composer require twig
    

    Then created my own twig service.

    getProjectDir());
    
            parent::__construct($loader);
        }
    }
    

    Now my email command looks like 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);
        }
    }
    

提交回复
热议问题