RenderView in My service

前端 未结 3 1356
别跟我提以往
别跟我提以往 2021-02-05 02:53

I\'m new of symfony world. I want to use render inside my service, but I got this error

Call to undefined method renderView

I know t

3条回答
  •  执笔经年
    2021-02-05 03:41

    You are correct about renderView(), it's only a shortcut for Controllers. When using a service class and inject the templating service, all you have to do is change your function to render() instead. So instead of

    return $this->renderView('Hello/index.html.twig', array('name' => $name));
    

    you would use

    return $this->render('Hello/index.html.twig', array('name' => $name));
    

    Update from Olivia's response:

    If you are getting circular reference errors, the only way around them is to inject the whole container. It's not considered best practice but it sometimes cannot be avoided. When I have to resort to this, I still set my class variables in the constructor so I can act as if they were injected directly. So I will do:

    use Symfony\Component\DependencyInjection\ContainerInterface;
    
    class MyClass()
    {
        private $mailer;
        private $templating;
    
        public function __construct(ContainerInterface $container)
        {
            $this->mailer = $container->get('mailer');
            $this->templating = $container->get('templating');
        }
        // rest of class will use these services as if injected directly
    }
    

    Side note, I just tested my own standalone service in Symfony 2.5 and did not receive a circular reference by injecting the mailer and templating services directly.

提交回复
热议问题