How to iterate over array of objects in Handlebars?
I meant in the template()
call..
You just need to pass the results as an object. So instead of calling
var html = template(data);
do
var html = template({apidata: data});
and use {{#each apidata}}
in your template code
demo at http://jsfiddle.net/KPCh4/4/
(removed some leftover if
code that crashed)
This fiddle has both each
and direct json. http://jsfiddle.net/streethawk707/a9ssja22/.
Below are the two ways of iterating over array. One is with direct json passing and another is naming the json array while passing to content holder.
Eg1: The below example is directly calling json key (data) inside small_data variable.
In html use the below code:
<div id="small-content-placeholder"></div>
The below can be placed in header or body of 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>
The below one is on document ready:
var small_source = $("#small-template").html();
var small_template = Handlebars.compile(small_source);
The below is the json:
var small_data = {
data: [
{username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
{username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" }
]
};
Finally attach the json to content holder:
$("#small-content-placeholder").html(small_template(small_data));
Eg2: Iteration using each.
Consider the below json.
var big_data = [
{
name: "users1",
details: [
{username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
{username: "allison1", firstName: "Allison", lastName: "House", email: "[email protected]" },
{username: "ryan1", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
]
},
{
name: "users2",
details: [
{username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
{username: "allison2", firstName: "Allison", lastName: "House", email: "[email protected]" },
{username: "ryan2", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
]
}
];
While passing the json to content holder just name it in this way:
$("#big-content-placeholder").html(big_template({big_data:big_data}));
And the template looks like :
<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>
You can pass this
to each block. See here: http://jsfiddle.net/yR7TZ/1/
{{#each this}}
<div class="row"></div>
{{/each}}