跳转到主要内容
dclnet 提交于 31 July 2015

原文链接:Debugging Twig templates

Twig模板引擎提供了一个调试工具。

Drupal 8 实现并且增加了一个额外的工具,可以让你找到输出标记(markup)的模板

开启调试(Enable debugging)

你要开启 Twig 的调试功能是在 sites/default/services.yml 里。

设置该文件中的debug变量为 true

parameters:
  twig.config:
    debug: true 

如果你用的是火狐,请确保“HTML”->“Show Comments”选项是开启(选中)的。

Firebug setting for twig debug

自动重新加载编译过的Twig模板

编译过的Twig模板是作为php类文件保存在硬盘中的,这样可以提升性能,但是这意味着你更改了模板源文件后它们不会及时更新显示出来。要开启Twig模板自动重新加载,在 services.yml 文件中设置 debug 为开启即可,关于此更多信息,可以查阅:https://drupal.org/node/1903374

输出变量

{{ dump() }}
{{ dump(var) }}

如果你安装了 Devel 子模块kint,你可以在twig模板中加入以下代码以获得可折叠显示的变量:

{{ kint() }}

以下是英文原文,可对照阅读

Last updated June 29, 2015. Created on February 3, 2013. Edited by wesruv, dawehner, Cottser, rpayanm. You can edit this page, too.

The Twig templating engine offers a debug tool.

The Drupal 8 implementation also adds an additional tool that allows you to locate the template that outputs the markup.

Enable debugging

You enable Twig Debugging in sites/default/services.yml.

Set the debug variable to true:

parameters:
  twig.config:
    debug: true 

In firebug make sure that "Show Comments" is enabled:

Firebug setting for twig debug

Automatic reloading Twig templates are compiled

Twig templates are compiled to PHP classes on disk for better performance, but this means by default your templates are not refreshed when you make changes. To enable automatic reloading of Twig templates, enable debug in services.yml. For more information, see https://drupal.org/node/1903374.

Printing variables

{{ dump() }} {{ dump(var) }}

If you have Devel's kint submodule you can get an accordion display of the variables available to twig with: