mustache.php

How to use loops with Mustache.php?


I need to loop as foreach() with my array,

$input = array (
  1 =>   array (    'year' => '1534',    'name' => 'test1',  ),
  2 =>   array (    'year' => '1644',    'day' => 'test2' )
  3 =>   array (    'year' => '2015',    'day' => 'test3',  ),
   // ...
);
$m->render( $template, $input );

but can't ref without a "rooot key"... This was the first problem... Then I sulve using $input = array('list'=>$input); and ok, now list key exist to {#list} test {/list} but it not loops (!), it shows "test" once...


Solution

  • I think the problem is inside the $input array. You shouldn't use the numeric keys. So try changing the array from

    $input = array (
          1 =>   array (    'year' => '1534',    'name' => 'test1',  ),
          2 =>   array (    'year' => '1644',    'day' => 'test2' )
          3 =>   array (    'year' => '2015',    'day' => 'test3',  ),
        );
    

    to

    $input = array (
          array (    'year' => '1534',    'name' => 'test1',  ),
          array (    'year' => '1644',    'day' => 'test2' )
          array (    'year' => '2015',    'day' => 'test3',  ),
        );
    

    This is a my example, a little bit different from your code:

        Mustache_Autoloader::register();
        $oMustache = new Mustache_Engine( array(
            'loader' => new Mustache_Loader_FilesystemLoader( 'templates' ),
        ));
    
        $aVariables = array(
            'list' => array(
                array( 'value' => 'one' ),
                array( 'value' => 'two' ),
                array( 'value' => 'three' ),
            )
        );
    
        $template = $oMustache->loadTemplate( 'my_template_name' );
        return $template->render( $aVariables );
    

    And this is the mustache template:

    {{#list}}
        test {{value}} <br/>
    {{/list}}