javascript Mustache 模板与对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8855078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mustache templating with an array of objects
提问by RyanP13
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:
使用 Mustache 我想使用以下模板枚举该对象:
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:
链接到这个问题的小提琴:
回答by nikoshr
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});
回答by gonchuki
You need to use Mustache's built-in iteration capabilities:
您需要使用 Mustache 的内置迭代功能:
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);
the secret sauce is in the section declaration {{#friends}}
秘诀在声明部分 {{#friends}}