PHP   发布时间:2022-04-04  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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 => $@R_675_7548@ {
        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模板的所有参数全部内容,希望文章能够帮你解决php-遍历传递给Twig模板的所有参数所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: