Search code examples
handlebars.js

Iterate {{#each }} certain times in HandlebarsJS


I have below code in HandlebarsJS.

   <thead>
        <tr>
            {{#each this.attr_name}}
                {{#if @index < 9}}
                    <th>{{ this }}</th>
                {{/if}}
            {{/each}}
        </tr>
    </thead>

But this line {{#if @index < 5}} is not working. I would like to iterate {{#each 8 times.


Solution

  • Handlebars does not have any built-in way to do comparison logic like @index < 9. You will need to create your own custom helper to do that.

    Fortunately, your problem can be solved with a very simple helper.

    For example, implement the @index < 9 comparison, you could create a helper that takes some number num and a comparison number comparator and returns true if num < comparator or else false:

    Handlebars.registerHelper('lessThan', (num, comparator) => num < comparator);
    

    To implement this helper in your template:

    {{#each this.attr_name}}
      {{#if (lessThan @index 8)}}
        <th>{{ this }}</th>
      {{/if}}
    {{/each}}
    

    Note: We are using 8 as the comparator argument instead of 9 because your question said you want eight items outputted and @index is 0-based, so: 0, 1, 2, 3, 4, 5, 6, 7 is eight items.

    Here is an example fiddle.

    An alternative approach would be to create a helper that takes an array and a count and returns the first count number of items in that array:

    Handlebars.registerHelper('first', (arr, count) => arr.slice(0, count));
    

    Using this helper in your template would simplify it to:

    {{#each (first this.attr_name 8)}}
      <th>{{ this }}</th>
    {{/each}}
    

    Here is a fiddle demonstrating this approach.