How to iterate over array in handlebar template without defined name in model
-
12-12-2019 - |
Question
I have model:
[
{
"ID": 5,
"email": "xx@vflbg.com"
},
{
"ID": 6495,
"email": "email@monkey.com"
}
]
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": "xx@vflbg.com"
},
{
"ID": 6495,
"email": "email@monkey.com"
}
]
I would simple iterate in handlebars like:
{{#each users}}
<p>{{email}}</p>
{{/each}}
Solution
If you have this:
var a = [
{
"ID": 5,
"email": "xx@vflbg.com"
},
{
"ID": 6495,
"email": "email@monkey.com"
}
];
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() });
OTHER TIPS
This works too:
{{#each this}}
<p>{{email}}</p>
{{/each}}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow