Render template from twig extension

后端 未结 3 630
说谎
说谎 2021-02-05 13:00

I have built a twig extension to do some things and one of them is render a template. How can I access from inside the twig extension the engine environment and call the Render

3条回答
  •  独厮守ぢ
    2021-02-05 13:05

    You can define the extension so that it needs the environment. Twig will automatically pass it to the function.

    use Twig\Environment;
    use Twig\TwigFunction;
    
    public function getFunctions()
    {
        return [
            new TwigFunction(
                'myfunction',
                [$this, 'myFunction'],
                ['needs_environment' => true]
            ),
        ];
    }
    
    public function myFunction(Environment $environment, string $someParam)
    {
        // ...
    }
    

    For older versions of Twig

    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction(
                'myfunction',
                array($this, 'myFunction'),
                array('needs_environment' => true)
            ),
        );
    }
    
    public function myFunction(\Twig_Environment $environment, string $someParam)
    {
        // ...
    }
    

提交回复
热议问题