编程语言
首页 > 编程语言> > php-遍历传递给Twig模板的所有参数

php-遍历传递给Twig模板的所有参数

作者:互联网

有谁知道如何循环传递到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文档,试图找到一个隐藏的宝石,该宝石揭示了如何执行此操作,但没有发现任何问题.

解决方法:

您需要为此创建自己的函数:

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 %}

标签:templates,symfony,twig,php
来源: https://codeday.me/bug/20191123/2064559.html