Handlebars – Must pass iterator to each (Error)

If you’re starting out with Handlebars and using it to create your HTML web pages, you may come across an oblique error message which may not make too much sense.

One such error you may encounter returns the following response:

throw new Exception(‘Must pass iterator to #each’)

To solve this problem you need to locate within your Handlebars template code an {{#each}} call.

For example, you may have something like this in your code where it is intended to loop through something and fetch the url and the link and output them as an anchor tag:

{{#each}}
    <a href="{{uri}}"">{{link}}</a>
{{/each}}

Solution

To solve this problem, with every {{#each}} call in your template amend it to {{#each .}} . If you missed it, there’s a space after the word each followed by a . (dot). This . dot sets the context of each to whatever you’ve passed in to the template.

Therefore, our example code above should now look like this:

{{#each .}}
    <a href="{{uri}}"">{{link}}</a>
{{/each}}

Once you’ve made this amendment you shouldn’t have this error any longer.

Ryan Sheehy

Author of scripteverything.com, Ryan has been dabbling in code since the late '90s when he cut his teeth by exploring VBA in Excel when trying to do something more. Having his eyes opened with the potential of automating repetitive tasks, he expanded to Python and then moved over to scripting languages such as HTML, CSS, Javascript and PHP. When he is not behind a screen, Ryan enjoys a good bush walk with the family during the cooler months, and going with them to the beach during the warmer months.

Recent Posts