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

标签 php templates symfony 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)
  }
}

我想遍历所有不是 subdata1subdata2 的参数,这样我就可以输出如下内容:

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/

相关文章:

php - 2 列中 float /内联 block 元素的间隙问题

php - PHP while 语句中的 Lambda 和冒号?

c++ - Variadic 用户定义的转换/构造函数

c++ - 丢失 const volatile 限定词

mysql - 预期查询生成器 SingleValuedAssociationField

php - ApiPlatform/Symfony - 生成资源路径

javascript - 如何删除任意框中上传的图片?

php - 为 JSON API 引用从 MySQL 返回的 PHP 数组

c++ - 指定可选模板参数的子集

Symfony 2 配置参数 - 必须定义该参数