This script has both each and direct json. http://jsfiddle.net/streethawk707/a9ssja22/ .
Below are two ways to iterate over an array. One of them is associated with the direct transfer of json, and the other with the name of the json array when transferring content to the owner.
Eg1: the example below directly calls the json key (data) inside the small_data variable.
In html, use the code below:
<div id="small-content-placeholder"></div>
Below you can put in the 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>
Below is the finished document:
var small_source = $("#small-template").html(); var small_template = Handlebars.compile(small_source);
Following is 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" } ] };
Finally, attach json to the content holder:
$("#small-content-placeholder").html(small_template(small_data));
Eg2: Iterate using each.
Consider json below.
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" } ] } ];
When passing json to the content holder, just name it like this:
$("#big-content-placeholder").html(big_template({big_data:big_data}));
And the template looks like this:
<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>