Render template from twig extension

后端 未结 3 628
说谎
说谎 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)
    {
        // ...
    }
    
    0 讨论(0)
  • 2021-02-05 13:10

    @tvlooy answer give me a hint but didn't work for me. What I needed to to to achieve it is:

    namespace AppBundle\Twig;
    
    
    class MenuExtension extends \Twig_Extension
    {
        public function getName()
        {
            return 'menu_extension';
        }
    
        public function getFunctions()
        {
           return [
               new \Twig_SimpleFunction('myMenu', [$this, 'myMenu'], [
                   'needs_environment' => true,
                   'is_safe' => ['html']
               ])
           ];
        }
    
        public function myMenu(\Twig_Environment $environment)
        {
              return $environment->render('AppBundle:Menu:main-menu.html.twig');
        }
    }
    

    I needed addtionaly add 'is_safe' => ['html'] to avoid autoescaping of HTML.

    I've also registered the class as symfony service:

    app.twig.menu_extension:
        class: AppBundle\Twig\MenuExtension
        public: false
        tags:
          - { name: twig.extension }
    

    in TWIG template I've added {{ myMenu() }}

    I work with "twig/twig": "~1.10"and Symfony 3.1.3 version

    0 讨论(0)
  • 2021-02-05 13:20

    Using this function the user can pass the twig environment instance to a twig extension

    private $environment;
    
    public function initRuntime(\Twig_Environment $environment)
    {
        $this->environment = $environment;
    }
    
    0 讨论(0)
提交回复
热议问题