Twig-如果启用了调试模式,则显示模板名称 [英] Twig - display template names if debug mode is enabled

查看:216
本文介绍了Twig-如果启用了调试模式,则显示模板名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近正在使用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并添加了

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 -->

这篇关于Twig-如果启用了调试模式,则显示模板名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆