0

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.

Ray Lawlor
  • 368
  • 1
  • 4
  • 13

1 Answers1

1

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...

Ray Lawlor
  • 368
  • 1
  • 4
  • 13
  • That's likely not your issue. Mustache is able to iterate over top level data as well, for example: `$m->render('{{#.}}x{{/.}}', [1,2,3]) == "xxx"`. Without seeing the full code and data you used for your original question, it's hard to say what your issue is, though. – bobthecow Mar 15 '16 at 17:44