这个小提琴既有each
直接的json。http://jsfiddle.net/streethawk707/a9ssja22/。
下面是遍历数组的两种方法。一种是直接传递json,另一种是传递给内容持有者时命名json数组。
范例1:以下示例直接在small_data变量中调用json键(数据)。
在html中,使用以下代码:
<div id="small-content-placeholder"></div>
以下内容可以放在html的标题或正文中:
<script id="small-template" type="text/x-handlebars-template">
<table>
<thead>
<th>Username</th>
<th>email</th>
</thead>
<tbody>
{{#data}}
<tr>
<td>{{username}}
</td>
<td>{{email}}</td>
</tr>
{{/data}}
</tbody>
</table>
</script>
以下文件已准备就绪:
var small_source = $("#small-template").html();
var small_template = Handlebars.compile(small_source);
下面是json:
var small_data = {
data: [
{username: "alan1", firstName: "Alan", lastName: "Johnson", email: "alan1@test.com" },
{username: "alan2", firstName: "Alan", lastName: "Johnson", email: "alan2@test.com" }
]
};
最后将json附加到内容持有者:
$("#small-content-placeholder").html(small_template(small_data));
实例2:使用每个迭代。
考虑下面的json。
var big_data = [
{
name: "users1",
details: [
{username: "alan1", firstName: "Alan", lastName: "Johnson", email: "alan@test.com" },
{username: "allison1", firstName: "Allison", lastName: "House", email: "allison@test.com" },
{username: "ryan1", firstName: "Ryan", lastName: "Carson", email: "ryan@test.com" }
]
},
{
name: "users2",
details: [
{username: "alan2", firstName: "Alan", lastName: "Johnson", email: "alan@test.com" },
{username: "allison2", firstName: "Allison", lastName: "House", email: "allison@test.com" },
{username: "ryan2", firstName: "Ryan", lastName: "Carson", email: "ryan@test.com" }
]
}
];
在将json传递给内容持有者时,只需以这种方式命名:
$("#big-content-placeholder").html(big_template({big_data:big_data}));
模板看起来像:
<script id="big-template" type="text/x-handlebars-template">
<table>
<thead>
<th>Username</th>
<th>email</th>
</thead>
<tbody>
{{#each big_data}}
<tr>
<td>{{name}}
<ul>
{{#details}}
<li>{{username}}</li>
<li>{{email}}</li>
{{/details}}
</ul>
</td>
<td>{{email}}</td>
</tr>
{{/each}}
</tbody>
</table>
</script>