How To: Handlebars - Iterate over Arrays with the Each Helper

The each helper is used to iterate over an array or an object.

Syntax

Within the Each helper, the current element becomes the context. The property refers to the property of the current element within the array or the current attribute within the object.

{{#each ArrayOrObject}}
    {{property}}
{{/each}}

Example with an Array of strings

The context is passed into the template as { types: types }. In the template, the each helper iterates over each string within the types array. Within the each helper, this is the string within the array.

var types = ["dog", "cat", "fish"];
 
var template = Handlebars.compile(
  "{{#each types}}" +
    "{{this}} " +
  "{{/each}}"
);
 
console.log(template({ types: types }));

The each helper with an Array of JSON elements

Array of people.

  var people = [
    { id: 1, firstName: "Anthony", lastName: "Nelson" },
    { id: 2, firstName: "Helen", lastName: "Garcia" },
    { id: 3, firstName: "John", lastName: "Williams" }
  ];

Handlebars template that uses the each helper to iterate over each JSON element.

{{#each people}}
  {{firstName}} {{lastName}}
{{/each}}

Example

The following example iterates over an array of JSON elements and creates the HTML for a select element with an option for each person in the array. The HTML that is generated is applied to a div element.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License