Twig - display template names if debug mode is enabled

前端 未结 3 574
一个人的身影
一个人的身影 2021-01-07 01:33

I\'m using Twig lately and I was wondering if it is possible to output the template names which are loaded on the page. The best way I can think of is to display the name ab

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-07 02:34

    Thanks Frank Hofmann yet another usefull feature is to render existing block begin/end within template as well. Beware that not all twig templates are purely HTML. HTML comments will break CSS or JS code. This can be avoided for example using naming conventions...

    _renderComment('BEGIN TEMPLATE: ' . $this->getTemplateName());
            $this->displayWithErrorHandling($this->env->mergeGlobals($context), array_merge($this->blocks, $blocks));
            $this->_renderComment('END TEMPLATE: ' . $this->getTemplateName());
        }
    
        public function displayBlock($name, array $context, array $blocks = [], $useBlocks = true)
        {
            $this->_renderComment('BEGIN BLOCK: ' . $name);
            parent::displayBlock($name, $context, $blocks, $useBlocks);
            $this->_renderComment('END BLOCK: ' . $name);
        }
    
        /**
         * @param string $comment
         */
        private function _renderComment($comment)
        {
            $extension = pathinfo($this->getTemplateName(), PATHINFO_EXTENSION);
            if (in_array($extension, [
                'css',
                'js',
            ])) {
                echo '/* ' . $comment . ' */';
            } else {
                echo '';
            }
        }
    }
    

提交回复
热议问题