欢迎光临
我们一直在努力

Drupal 8中调试Twig模板中的变量教程

常言:工欲善其事,必先利其器。Drupal 主题开发中技巧也不少,学会这些技巧会起到事半功倍的效果。今天给大家推介的是如何调试打印出Twig模板中的变量,不妨一看!Oops,Drupal 8!

在drupal 8 twig模板中,你可以在注释中找到大部分、常用的模板变量。但是,当一些模块或者主题引入新变量的时候,该怎么办呢?

Twig模板提供了一个函数——‘dump’,方便你去发现、检查这些变量。

使用‘dump’函数有个小前提,你需要启用twig的debug模式。关于如何启用twig的debug模式 https://www.drupal.org/node/1903374。

检查单个变量

{{ dump(title) }}

简单吧!

那我想看所有的变量,怎么整?

找出所有变量

{{ dump() }}

找出变量可用的key

{{ dump(_context|keys) }}

Twig中的全局可用变量

There are additional global variables available in all Twig templates:
_self references the current template and contains advanced information about a template, i.e. the compiled template class name and information about the Twig environment.
_context references the current context and contains all variables passed to the template such as variables sent from theme(), prepared by preprocess, or set in the template. Adding {{ dump() }} without specifying a variable is equivalent to {{ dump(_context) }}.
_charset references the current charset.

友情提示

如果你想查看所有的变量,但是‘dump’函数因为递归等原因把内存耗尽了,你可以通过以下方式来处理:

<ol>
{% for key, value in _context %}
<li>{{ key }}</li>
{% endfor %}
</ol>

然后用一个约束条件去检查这些变量,如 { if loop.index = 2 %} 这样就可以找到你所需要的内容啦!

赞(1)
版权归原作者所有,如有侵权请告知。达维营-前端网 » Drupal 8中调试Twig模板中的变量教程

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址