有谁知道如何循环遍历传递给 Twig 模板的所有参数,而事先不知道它们的名称?
{{ dump() }}
函数(调用 var_dump()
)输出如下内容:
array(5) {
["foo"]=>
bool(true)
["bar"]=>
string(3) "Yes"
["baz"]=>
int(99)
["subdata1"]=>
array(1) {
["foo2"]=>
bool(false)
}
["subdata2"]=>
array(1) {
["foo3"]=>
int(5)
}
}
我想遍历所有不是 subdata1
或 subdata2
的参数,这样我就可以输出如下内容:
foo is true
bar is Yes
baz is 99
保留发送到模板的数据结构很重要,因此我正在管道的 Twig 端寻找解决方案。
在过去的两天里,我浏览了稀疏的 Twig 文档,试图找到一个隐藏的 gem 来揭示如何做到这一点,但一无所获。
最佳答案
您需要为此创建自己的函数:
function get_other_context_vars($context)
{
$vars = array();
foreach ($context as $key => $value) {
if (!$value instanceof Twig_Template && !in_array($key, array('subdata1', 'subdata2')) {
$vars[$key] = $value;
}
}
return $vars;
}
$environment->addFunction(new Twig_SimpleFunction('get_other_context_vars', 'get_other_context_vars', array('needs_context' => true)));
用法:
{% for name, var in get_other_context_vars() -%}
{{ name }} is {{ var }}
{%- endfor %}
关于php - 遍历传递给 Twig 模板的所有参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17612322/