twig - pass function into template

后端 未结 5 1038
清歌不尽
清歌不尽 2021-02-05 05:31

Currently I place my function in a class and pass an instance of this class into template and call my required function as a class method.

{{ unneededclass.blah(         


        
5条回答
  •  醉酒成梦
    2021-02-05 06:07

    Using Anonymous class

    Create anonymous class in manager/controller/service ..

         $functions = new class($router)
        {
            public function __construct($router)
            {
                $this->router = $router;
            }
    
        public function getRowUrl(FileManager $fileManager)
        {
            if ($fileManager->isNode()) {
                return $this->router->generate('...', ['parent' => ...]);
            }
            return $this->router->generate('...', ['entity' => ...]);
        }
    };
    

    Paste parameter into view

    $params=[
                'functions' => $functions
    
            ];
    
    
    
        return new Response($this->twig->render('...:index.html.twig', $params));
    

    Use function in view

     {% set rowUrl = functions.rowUrl(entity) %}
    

提交回复
热议问题