如何从Twig模板中检索所有变量? [英] How to retrieve all Variables from a Twig Template?

查看:74
本文介绍了如何从Twig模板中检索所有变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用PHP检索Twig模板中的所有变量?

Is it possible to retrieve all variables inside a Twig template with PHP?

例如someTemplate.twig.php:

Example someTemplate.twig.php:

Hello {{ name }}, 
your new email is {{ email }}

现在我想做这样的事情:

Now I want to do something like this:

$template = $twig->loadTemplate('someTemplate');
$variables = $template->getVariables();

$变量现在应包含名称"和电子邮件".

$variables should now contain "name" and "email".

我要这样做的原因是我正在CMS系统上工作 我的用户动态设置我的树枝模板和变量的位置 并且它们还通过API填充变量.

The reason I want to do this is that I am working on a CMS system where my twig templates and variables are dynamically set by my users and they also fill the variables through an API.

我想将默认值设置为未设置的变量,因此我 需要模板中存在的所有变量的列表...

I want to set default values to not-set variables and therefore I need a list of all variables that exist inside the template…

推荐答案

UPDATE 2019

尽管{{ dump() }}确实有效,但在某些情况下,如果它生成太多信息(例如,由于递归),则可能会导致PHP出现内存耗尽"错误.在这种情况下,请尝试{{ dump(_context|keys) }}按名称获取已定义变量的列表,而不转储其内容.

Although {{ dump() }} does work, in some circumstances it may result in a "memory exhausted" error from PHP if it generates too much information (for example, due to recursion). In this case, try {{ dump(_context|keys) }} to get a list of the defined variables by name without dumping their contents.

UPDATE 2017

可以使用{{ dump() }}过滤器.感谢您在评论中指出这一点!

It is possible by using {{ dump() }} filter. Thanks for pointing that out in the comments!

过时

不可能.

您可以在树枝模板中查找这些变量,然后向其中添加|default('your_value')过滤器.它将检查变量是否已定义并且不为空,如果没有,则将其替换为您的值.

You can look for these variable in twig templates and add |default('your_value') filter to them. It will check if variable is defined and is not empty, and if no - will replace it with your value.

这篇关于如何从Twig模板中检索所有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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