【问题标题】:Consuming complex array with keys in php mustache在 php mustache 中使用带有键的复杂数组
【发布时间】:2013-03-26 05:02:16
【问题描述】:

我有以下数组结构arr

Array
(
    [1] => Array
        (
            [width] => 600 
            [pages] => Array
                (
                    [0] => Array
                        (
                            [bgColor] => 'red' 
                        )



                ) 
        )

    [3] => Array
        (
            [width] => 400 
            [pages] => Array
                (
                    [0] => Array
                        (
                            [bgColor] => 'blue' 
                        )



                ) 
        )

)

目前我将数据传递为,

$tpl->render(array( 
   'arr'   => new ArrayIterator($arr)                       
));

在 mustache 模板中,我正在使用它,

{{#arr}}  
  {{width}}
{{/arr}}

它正确地给了我width。但现在我想要该数组的keys1 用于第一个,3 用于第二个)以及pages 键中的元素总数。

这个小胡子怎么办?

【问题讨论】:

  • 在此答案中将 ArrayIterator 替换为 Presenter 类:stackoverflow.com/a/15619309/213448
  • @bobthecow,我以前从未与ArrayIterator 合作过。你能澄清一下这有什么帮助吗?另外,我不确定在哪里放置这些课程?我特别在 wp 工作。除了提供结构之外,该课程还会帮助我吗?
  • IteratorPresenter 是一个 Presenter(或 ViewModel),它为原始数组中的每个元素提供隐式的 keyvaluefirstlast 属性。它是一个通用 Presenter,适用于任何数组或可迭代对象,但如果您有更具体的需求,您也可以为您的数据集制作一个 Presenter。有关演示者的更多信息,请参见 Wikipedia — hile.mn/12lVbky

标签: php arrayiterator mustache.php


【解决方案1】:

好的,我知道 mustache 无法跟踪数组的 index,它需要 hash 中的所有内容。

所以,我正在使用以下技术,它有效但有点难看。

function prepareForMustache ($arr) {
    foreach($arr as $k => &$v) {
        $v['key']  = $k;
        $v['pagesCount'] = count($v['pages']);
    } 
}


$arr = prepareForMustache($arr);

$tpl->render(array( 
   'arr'   => new ArrayIterator($arr)                       
));

在 mustache 模板中消费为,

{{#arr}}  
  {{width}}
  {{key}}
  {{pagesCount}}
{{/arr}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-04
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    相关资源
    最近更新 更多