How to get current template name in a TWIG function

后端 未结 3 538
无人共我
无人共我 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:10

    For everyone who needs an answer to the initial question, I found a solution that twig itself is using in the Twig_Error class.

    protected function guessTemplateInfo()
    {
        $template = null;
        foreach (debug_backtrace() as $trace) {
            if (isset($trace['object']) && $trace['object'] instanceof Twig_Template && 'Twig_Template' !== get_class($trace['object'])) {
                $template = $trace['object'];
            }
        }
    
        // update template filename
        if (null !== $template && null === $this->filename) {
            $this->filename = $template->getTemplateName();
        }
    
        /* ... */
    

    best regards!

提交回复
热议问题