See The Spark blogs

Handlebars helper arrays

Problem

Today I encountered a problem with Handlebars templating where I wanted to return an array from a helper and iterate through it with the #each built in helper. Handlebars is running server side with Node.js and Express.

First attempt

I started by trying something line this:

.js:

var hbs = require('hbs');
var myArray = ['AA', 'BB', 'CC'];
hbs.registerHelper('myList', function() { return myArray; });

template:

{{myList}} <!-- This shows the values from my array -->
{{#each myList}}
    {{this}} <!-- This never renders -->
{{/each}}

My solution

Because I could get the array to print out in a {{}} block I thought the helper was OK but it turned out not to be the case.

.js:

var hbs = require('hbs');
var myArray = ['AA', 'BB', 'CC'];
hbs.registerHelper('myList', function(options) { return options.fn(myArray); } );

template:

{{#myList}}
{{#each this}}
    {{this}} 
{{/each}}
{{/myList}}

In my case {{this}} is an object so I used its property names but the principal is the same.

I couldn't find this example online so I thought it worth putting it here. I hope it helps someone.

Date published: 2016-12-03
Last updated: 2016-12-03
Add a comment You must be logged in and have confirmed your email to comment. Sign in