我正在尝试渲染模型对象中的每个数组值。我可以设法渲染数组的第一个值,但不能渲染其余的数组。我已尝试在每个功能内部工作,但不起作用。我需要查看每一行中的所有数组值。请检查示例,您将很快看到:
Here is working sample which renders only first value of the array: http://jsfiddle.net/N2b5M/1123/
模板:
{{#users}}
<tr>
<td>{{fullName person}}</td>
<td>{{jobTitle}}</td>
<td><a href="https://twitter.com/{{twitter}}">@{{twitter}}</a></td>
<td>{{currentDate}}</td>
</tr>
{{/users}}
数据:
var data = {
users: [ {
person: {
firstName: "Garry",
lastName: "Finch",
tags: [
{
"type": "P",
"date": "10.9.2014"
},
{
"type": "C",
"date": "18.12.2014"
},
{
"type": "T",
"date": "2.10.2014"
}
]
},
jobTitle: "Front End Technical Lead",
twitter: "gazraa"
}, {
person: {
firstName: "Garry",
lastName: "Finch",
tags: [
{
"type": "T",
"date": "2.11.2014"
}
]
},
jobTitle: "Photographer",
twitter: "photobasics"
}, {
person: {
firstName: "Garry",
lastName: "Finch",
tags: [
{
"type": "T",
"date": "11.12.2014"
}
]
},
jobTitle: "LEGO Geek",
twitter: "minifigures"
} ]
};
的javascript:
var source = $("#some-template").html();
var template = Handlebars.compile(source);
Handlebars.registerHelper('fullName', function(person) {
return person.firstName + " " + person.lastName;
});
Handlebars.registerHelper('currentDate', function(context) {
var currentTag = this.person.tags[0];
var currentDate = currentTag.date;
return currentDate;
});
$('body').append(template(data));
我正在尝试在tags数组中渲染所有日期并尝试这样:
{{#each person.tags}}
<td>{{currentDate}}</td>
{{/each}}
Handlebars.registerHelper('each', function(context, options) {
var tagsTotal = context.person.tags.length;
var ret = '';
console.log(tagsTotal);
for( i = 0; i < tagsTotal; i++) {
var tagType = context.type;
ret += options.fn(context[i]);
}
return ret;
});
答案 0 :(得分:2)
我不确定这是否丑陋或是否有更好的方法。但这很有效:
<h1>Handlebars JS Example</h1>
<script id="some-template" type="text/x-handlebars-template"> <table>
<thead>
<th>Name</th>
<th>Job Title</th>
<th>Twitter</th>
<th>Dates</th>
</thead>
<tbody>
{{#users}}
<tr>
<td>{{fullName person}}</td>
<td>{{jobTitle}}</td>
<td><a href="https://twitter.com/{{twitter}}">@{{twitter}}</a></td>
{{#person}}
{{#tags}}
<td>
{{date}}
</td>
{{/tags}}
{{/person}}
</tr>
{{/users}}
</tbody>
</table>
</script>