Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mustache templating with an array of objects

I am trying to template the following array of objects:

var arr = [{name:"Ryan Pays", url:"http://www.ryanpays.com"}, {name:"foo", url:"http://www.google.com"}];

I convert that array to an object like so:

arr = $.extend({}, arr);

Which gives me the following object:

{
0:{name:"Ryan Pays", url:"http://www.ryanpays.com"},
1:{name:"foo", url:"http://www.google.com"}
}

Using Mustache i want to enumerate over that object with the following template:

var template = "<h4>Your friends' choices</h4>" +
               "<ul>" +
               "<li>" +
               "<p><strong>{{name}}</strong> likes <a href='{{url}}'>this</a></p>" +
               "</li>" +
               "</ul>";
var html = Mustache.to_html(template, displayData);
$('.choices').html(html);

I don't seem to be able to do that. I can get the first result like to print like so:

var html = Mustache.to_html(template, displayData[0]);

And so on but not both.

Link to fiddle of this issue:

http://jsfiddle.net/AtJDa/

like image 417
RyanP13 Avatar asked Jan 13 '12 18:01

RyanP13


2 Answers

You could use the template for arrays :

var template = "<h4>Your friends' choices</h4>" +
    "<ul>" +
           "{{#arr}}"+
           "<li>" +
           "<p><strong>{{name}}</strong> likes <a href='{{url}}'>this</a></p>" +
           "</li>" +
           "{{/arr}}"+
    "</ul>";
var html = Mustache.to_html(template, {arr:arr});
like image 109
nikoshr Avatar answered Nov 09 '22 13:11

nikoshr


You need to use Mustache's built-in iteration capabilities:

var template = "<h4>Your friends' choices</h4>" +
               "<ul>{{#friends}}" +
                 "<li>" +
                   "<p><strong>{{name}}</strong> likes <a href='{{url}}'>this</a></p>" +
                 "</li>" +
               "{{/friends}}</ul>";

var data = {friends: [{name:"Ryan Pays", url:"http://www.ryanpays.com"}, {name:"foo", url:"http://www.google.com"}]};

var html = Mustache.to_html(template, data);

http://jsfiddle.net/AtJDa/1/

the secret sauce is in the section declaration {{#friends}}

like image 37
gonchuki Avatar answered Nov 09 '22 11:11

gonchuki