symfonyrendersymfony-3.4

RenderView in Symfony Helper usage


How can I use $this->renderView inside a Symfony helper class (not inside a controller)? I'm new about the function renderView but what do I have to setup to use it within the Helper class?


Solution

  • You can inject twig as a service with autowiring

    <?php
    
    namespace App\My\Ns;
    
    use Twig\Environment;
    
    class Helper
    {
        public function __construct(
            protected Environment $environment
        ) {
        }
    
        public function method()
        {
            $html = $this->environment->render('my/template.html.twig', [/*  vars */]);
        }
    }