How to iterate over array in handlebar template without defined name in model
10,083
Solution 1
If you have this:
var a = [
{
"ID": 5,
"email": "[email protected]"
},
{
"ID": 6495,
"email": "[email protected]"
}
];
Then just supply the desired name when you call the compiled template:
var t = Handlebars.compile($('#t').html());
var h = t({ users: a });
That will leave you with your desired HTML in h
.
Demo: http://jsfiddle.net/ambiguous/ZgVjz/
If you have a collection built from the data:
var c = new C(a);
Then you'd call the template like this:
var h = t({ users: c.toJSON() });
Demo: http://jsfiddle.net/ambiguous/uF3tj/
Solution 2
This works too:
{{#each this}}
<p>{{email}}</p>
{{/each}}
Related videos on Youtube
Comments
-
jmav almost 2 years
I have model:
[ { "ID": 5, "email": "[email protected]" }, { "ID": 6495, "email": "[email protected]" } ]
Code for iterating in handlebars:
{{#each xxx}} <p>{{email}}</p> {{/each}}
how do I define xxx ?
If JSON had name in model like:
users: [ { "ID": 5, "email": "[email protected]" }, { "ID": 6495, "email": "[email protected]" } ]
I would simple iterate in handlebars like:
{{#each users}} <p>{{email}}</p> {{/each}}
-
Andrew Miner almost 10 yearsI'd recommend changing your accepted answer to Dave Stibrany's answer below. Definitely seems like the better way to do this.
-
-
MusikPolice over 10 yearsThis works, but the answer from Dave Stibrany below is a much better solution.
-
Pallavi almost 4 yearswhere to specify the list