Search code examples
handlebars.js

Adding offset to {{@index}} when looping through items in Handlebars


I'm iterating over a list in Handlebars using the built-in each helper. Within the each block, I'm referencing the current loop index {{@index}} to print the consecutive number of an item:

<script id="list-item-template" type="text/x-handlebars-template">
    {{#each items}}
    <li class="topcoat-list__item">
        <a href="#{{@index}}">Item number {{@index}}</a>
    </li>
    {{/each}}
</script>

This gives the following output:

  • Item number 0
  • Item number 1
  • Item number 2
  • ....

The problem is that I want to display an offsetted index which starts with 1 instead of 0.

I tried to perform calculations on the index like {{@index+1}}, but this just leads to an

Uncaught Error: Parse error


Solution

  • Handlebars gives you the possibility to write a custom helper that handles this situation, e.g. a helper function that lets you perform calculations on expressions like addition and subtraction etc.

    Below function registers a new helper, which simply increments a value by 1:

    var Handlebars = require('handlebars');
    
    Handlebars.registerHelper("inc", function(value, options)
    {
        return parseInt(value) + 1;
    });
    

    You can then use it within the handlebar expression using the inc keyword, like:

    {{inc @index}}