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

查看:24
本文介绍了如何从 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 现在应该包含name"和email".

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

2017 年更新

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

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

过时

这是不可能的.

您可以在 twig 模板中查找这些变量并向它们添加 |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天全站免登陆