phparrayiteratormustache.php

Consuming complex array with keys in php mustache


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 ?


Solution

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