Building a Handlebars "each with index" helper

Here's a super quick post about building a Handlebars helper in an Ember app for numbering lists in the context of an {{each}} iteration in Handlebars. Because don't we all want to display dynamically numbered lists in our Handlebars template.

Accessing an array's index

We can access the index number of an array element when iterating over a collection of (in this case) Ember objects.

Here's an example:

//some-template.hbs

{{#each model as |song index|

 Song No {{index}}: {{song.name}}

{{/each}}

This, however, will give us a numbered list that starts at 0. That is not how most muggles prefer to number lists. Unfortunately for us,

{{index + 1}}}

is not a thing. So, in order to get a properly numbered list, we need to build a Handlebars helper.

Let's do it!

Building the list-item helper

In app/helpers create a file, list-item.js. Define your helper here to take in an argument of the index number and return the index number incremented by 1:

import Ember from 'ember';

export default Ember.HTMLBars.makeBoundHelper(function(indexNum){ 
  return indexNum[0] + 1;

});

Then, utilize it like this in your template:


//some-template.hbs

{{#each model as |song index|

 Song No. {{list-item index}}: {{song.name}}

{{/each}}

That's it!

subscribe and never miss a post!

Blog Logo

Sophie DeBenedetto

comments powered by Disqus
comments powered by Disqus