Twig - 如果启用调试模式,则显示模板名称模板、名称、模式、Twig

由网友(拒绝暧昧)分享简介:我最近在使用 Twig,我想知道是否可以输出页面上加载的模板名称.我能想到的最好方法是在模板本身上方显示名称作为 html 注释.I'm using Twig lately and I was wondering if it is possible to output the template names which...

我最近在使用 Twig,我想知道是否可以输出页面上加载的模板名称.我能想到的最好方法是在模板本身上方显示名称作为 html 注释.

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 above the template itself as a html comment.

<!-- start @default/_components/_wrapper/form-wrapper.html.twig -->
    <form>
       ...
    </form>
<!-- end @default/_components/_wrapper/form-wrapper.html.twig -->

我知道我可以通过插入 {{ _self.templateName }} 来获取模板名称,但我不喜欢将它添加到每个模板或部分模板中.

I know that I can get the template name by inserting {{ _self.templateName }} but I don't like to add it to every template or partial.

该解决方案应该适用于 {% include %}{% use %} 等,如果它只是在启用调试模式时发生也很好.

The solution should work for {% include %}, {% use %} etc and it would also be nice if it just happens when debug mode is enabled.

我试图写一个扩展,但无论我怎么写,我都必须在每个模板中进行某种调用.

I tried to write an extension but no matter how I put it, I have to make some kind of call in each template.

这背后的原因是,随着项目越来越大,我试图减少搜索其他人实施的模板的时间.

The reason behind this is I'm trying to reduce the time searching for the templates somebody else implemented since the project is getting bigger and bigger.

注意:我不使用 Symfony.

Note: I'm NOT using Symfony.

提前致谢,感谢您的帮助!

Thanks in advance, any help is appreciated!

推荐答案

感谢@DarkBee,我被指出了正确的方向并最终使用了这个:我创建了一个 debug-template.class.php 内容如下:

Thanks to @DarkBee I was pointed to the right direction and ended up using this: I created a debug-template.class.php with the following content:

<?php

abstract class DebugTemplate extends Twig_Template {

    public function display(array $context, array $blocks = array())
    {
        // workaround - only add the html comment when the partial is loaded with @
        if(substr($this->getTemplateName(),0,1) == '@') {
            echo '<!-- START: ' . $this->getTemplateName() . ' -->';
        }

        $this->displayWithErrorHandling($this->env->mergeGlobals($context), array_merge($this->blocks, $blocks));

        if(substr($this->getTemplateName(),0,1) == '@') {
            echo '<!-- END: ' . $this->getTemplateName() . ' -->';
        }

    }
}
?>

然后我拿了我的 index.php 并添加了

Then I took my index.php and added

require_once 'vendor/twig/twig/lib/Twig/TemplateInterface.php';
require_once 'vendor/twig/twig/lib/Twig/Template.php';

并添加了DebugTemplate类

and added the DebugTemplate class

$twig = new Twig_Environment($loader, array(
    'cache' => false,
    'base_template_class' => 'DebugTemplate'
));

结果正是我想要的,看起来像这样

The result is just what I want and looks like this

<!-- START: @default/_components/panel.html.twig -->
        <div class="panel panel-default">
<!-- END: @default/_components/panel.html.twig -->
阅读全文

相关推荐

最新文章