Sometimes, we want to iterate over an object with JavaScript and Handlebars.js.
In this article, we’ll look at how to iterate over an object with JavaScript and Handlebars.js.
How to iterate over an object with JavaScript and Handlebars.js?
To iterate over an object with JavaScript and Handlebars.js, we can use the #each
keyword.
For instance, we write:
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min.js"></script>
<script id="some-template" type="text/x-handlebars-template">
<option value="none">select</option>
{{#each data}}
<optgroup label="{{@key}}">
{{#each this}}
<option value="{{id}}">{{name}}</option>
{{/each}}
</optgroup>
{{/each}}
</script>
<select>
</select>
to add the Handlebars script and the template for looping through each entry in data
.
We use #each this
to loop through each array property.
@key
returns the property name.
Then we write:
const source = $("#some-template").html();
const template = Handlebars.compile(source);
const data = {
data: {
fruit: [{
id: 1,
name: "banana"
}, {
id: 2,
name: "apple"
}],
vegetables: [{
id: 1,
name: "broccoli"
}]
}
}
$('select').append(template(data));
to select the template script tag and return its HTML code with:
const source = $("#some-template").html();
Then we compile the template with:
const template = Handlebars.compile(source);
And finally, we render the template with the data
with:
$('select').append(template(data));
Now we should see a drop down with the option groups rendered from the data
object.
Conclusion
To iterate over an object with JavaScript and Handlebars.js, we can use the #each
keyword.