mustachemustache.php

How to Iterate an array of objects in Mustache


I've got an array of objects being set to the Mustache render function:

 require 'vendor/Mustache/Autoloader.php';
    Mustache_Autoloader::register();
    $m = new Mustache_Engine();

echo $m->render($template, $data);

$data contains an array of objects, like this:

enter image description here

(This is a screenshot from http://www.jsoneditoronline.org and I've opened one of the objects for your information)

Now in my $template code I have this:

         {{#.}} 
                <article>

                    <h1>
                        <a href="layouts_post.html">{{name}}</a>
                    </h1>

                    <p>{{{text}}}</p>

                    <h2>{{jobtitle}}</h2>

                </article>
         {{/.}}

The iteration isn't working and I'm wondering if there is a way for Mustache to iterate through an array of objects as above.

(FYI - I've tried rebuilding my data, but without success. each time Mustache is not able to iterate.)

Many thanks for help in advance.


Solution

  • Ok I worked this out...

    In order for Mustache to have a containing variable, it needs to be assigned as a parameter in the render function. so to get this to work I assigned the $data array to a 'data' key:

    require 'vendor/Mustache/Autoloader.php';
    Mustache_Autoloader::register();
    $m = new Mustache_Engine();
    
    echo $m->render($template, array('data' => $data));
    

    So now 'data' becomes the lead var in the mustache template:

           {{#data}} 
                    <article>
    
                        <h1>
                            <a href="layouts_post.html">{{name}}</a>
                        </h1> 
    
                        <p>{{{text}}}</p>
    
                        <h2>{{jobtitle}}</h2>
    
                    </article>
           {{/data}}
    

    In fact it turns out you can assign a whole host of arrays in this function and have them available in the template layout:

    require 'vendor/Mustache/Autoloader.php';
    Mustache_Autoloader::register();
    $m = new Mustache_Engine();
    
    echo $m->render($template, array('data' => $data, 'anotherValue' => $someOtherData));
    

    Seems obvious I know...