This might seem a silly question but I can't seem to find the answer anywhere.
I'm hitting this Web API that returns an array of objects in JSON format:
Handlebars docs shows the following example:
<ul class="people_list">
{{#each people}}
<li>{{this}}</li>
{{/each}}
</ul>
In the context of:
{
people: [
"Yehuda Katz",
"Alan Johnson",
"Charles Jolley"
]
}
In my case I don't have a name for the array, it's just the root object of the response. I've tried using {{#each}}
with no luck.
First time using Handlebars... What am I missing?
UPDATE
Here's a simplified fiddle to show you what I'm asking: http://jsfiddle.net/KPCh4/2/
Does handlebars require the context variable to be an object and not an array?
Using
this
and{{this}}
. See code below in node.js:Console log output:
Handlebars can use an array as the context. You can use
.
as the root of the data. So you can loop through your array data with{{#each .}}
.I meant in the
template()
call..You just need to pass the results as an object. So instead of calling
do
and use
{{#each apidata}}
in your template codedemo at http://jsfiddle.net/KPCh4/4/
(removed some leftover
if
code that crashed)You can pass
this
to each block. See here: http://jsfiddle.net/yR7TZ/1/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:
The below can be placed in header or body of html:
The below one is on document ready:
The below is the json:
Finally attach the json to content holder:
Eg2: Iteration using each.
Consider the below json.
While passing the json to content holder just name it in this way:
And the template looks like :