twig - pass function into template

后端 未结 5 1045
清歌不尽
清歌不尽 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:09

    Full answer: http://twig.sensiolabs.org/doc/advanced.html#id2

    I prefer to use Twig Extension like this:

    namespace Some\Twig\Extensions;
    
    class MenuExtensions extends \Twig_Extension
    {
        public function getFunctions()
        {
            return array(
                new \Twig_SimpleFunction('sidebar_menu', [$this, 'generate_sidebar_menu']),
            );
        }
    
        public function generate_sidebar_menu($menu){
            return $menu;
        }
    
        public function getName()
        {
            return 'menu';
        }
    }
    

    In template:

    {{ sidebar_menu('some text') }}
    

提交回复
热议问题