Fra*_*ann 5 twig twig-extension
我最近正在使用 Twig,我想知道是否可以输出页面上加载的模板名称。我能想到的最好方法是将名称显示在模板本身上方作为 html 注释。
<!-- start @default/_components/_wrapper/form-wrapper.html.twig -->
<form>
...
</form>
<!-- end @default/_components/_wrapper/form-wrapper.html.twig -->
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过插入来获取模板名称{{ _self.templateName }},但我不喜欢将其添加到每个模板或部分模板中。
该解决方案应该适用于等{% include %},{% use %}如果它只是在启用调试模式时发生,那就太好了。
我尝试编写一个扩展,但无论我如何表达,我都必须在每个模板中进行某种调用。
这背后的原因是我试图减少搜索其他人实现的模板的时间,因为项目变得越来越大。
注意:我没有使用 Symfony。
提前致谢,感谢任何帮助!
感谢@DarkBee,我被指出了正确的方向并最终使用了这个:我创建了一个debug-template.class.php包含以下内容的:
<?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() . ' -->';
}
}
}
?>
Run Code Online (Sandbox Code Playgroud)
然后我拿走了我的index.php并添加了
require_once 'vendor/twig/twig/lib/Twig/TemplateInterface.php';
require_once 'vendor/twig/twig/lib/Twig/Template.php';
Run Code Online (Sandbox Code Playgroud)
并添加了 DebugTemplate 类
$twig = new Twig_Environment($loader, array(
'cache' => false,
'base_template_class' => 'DebugTemplate'
));
Run Code Online (Sandbox Code Playgroud)
结果正是我想要的,看起来像这样
<!-- START: @default/_components/panel.html.twig -->
<div class="panel panel-default">
<!-- END: @default/_components/panel.html.twig -->
Run Code Online (Sandbox Code Playgroud)