0

I have following structure of array arr

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



                ) 
        )

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



                ) 
        )

)

Currently I am passing data as,

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

In in mustache template, I am consuming it like,

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

It gives me width correctly. But now I want the keys of that array ( 1 for first and 3 for second one) and also the total no of elements in pages key.

How can I do this mustache ?

Jashwant
  • 28,410
  • 16
  • 70
  • 105
  • Replace your `ArrayIterator` with the Presenter class in this answer: http://stackoverflow.com/a/15619309/213448 – bobthecow Apr 04 '13 at 13:32
  • @bobthecow, I have never worked with `ArrayIterator` before. Can you clarify how's that gonna help ? Also, I am not exactly sure where to put this classes ? I am particularly working in wp. Will that class help me other than giving structure ? – Jashwant Apr 04 '13 at 14:54
  • The `IteratorPresenter` is a Presenter (or ViewModel) that provides an implicit `key`, `value`, `first` and `last` property for each element in your original array. It's a generic Presenter, meant for use with any array or iterable, but you could also make a Presenter for just your data set if you have more specific needs. See Wikipedia for more on Presenters — http://hile.mn/12lVbky – bobthecow Apr 04 '13 at 16:47

1 Answers1

1

Okay, I understand that mustache cannot keep track of index of array and it needs everything in hash.

So, I am using following technique, it works but little bit ugly.

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)                       
));

And consuming in mustache template as,

{{#arr}}  
  {{width}}
  {{key}}
  {{pagesCount}}
{{/arr}}
Ash
  • 3,242
  • 2
  • 23
  • 35
Jashwant
  • 28,410
  • 16
  • 70
  • 105