Mustache templating with an array of objects

那年仲夏 提交于 2019-12-03 04:22:21

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});

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!