How to get current template name in a TWIG function

后端 未结 3 506
无人共我
无人共我 2021-01-19 08:43

let\'s say I have created a custom twig function: templateName.

$twig = new Twig_Environment($loader);
$twig->addFunction(\'templateName\', new Twig_Func         


        
3条回答
  •  离开以前
    2021-01-19 09:32

    The solution proposed by Mario A did not work for me, but using debug_backtrace() is a great idea and a little modification made it work with a recent Twig version:

        private function getTwigTemplateName()
    {
        foreach (debug_backtrace() as $trace) {
            if (isset($trace['object']) 
                 && (strpos($trace['class'], 'TwigTemplate') !== false) 
                 && 'Twig_Template' !== get_class($trace['object'])
            ) {
                return $trace['object']->getTemplateName() . "({$trace['line']})";
            }
        }
        return '';
    }
    

提交回复
热议问题