3

I would like to add a counter in a table using Handlebars templating. I have a Handlebars template like so:

<script type="text/template" id="user-home-main-table-template">

    <% var i=0 %>
    <table class="table">
        <thead>
        <tr>
            <th>#</th>
            <th>Team Name</th>
            <th>Club</th>
            <th>Sport</th>
            <th>Delete?</th>
        </tr>
        </thead>
        <tbody>
        {{#teams}}
        <tr>
            <td><%=i%></td>
            <td>{{teamName}}</td>
            <td>{{club}}</td>
            <td>{{sport}}</td>
            <td>delete</td>
        </tr>
        {{/teams}}
        </tbody>
    </table>
</script>

this works, but the variable i doesn't increment, what's the best way to solve this problem?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • looks like this is close http://stackoverflow.com/questions/11884960/how-to-get-index-in-handlebars-each-helper but it might be outdated – Alexander Mills Jan 18 '15 at 07:10

2 Answers2

5

You can use {{@index}} to access the current index

{{#each array}}
  {{@index}}: {{this}}
{{/each}}

But this index will start with 0 which sometimes you probably don't want.

In that case you can create and register helper method to increment the index.

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}}

But if you do not want to do that there is another simpler way to achieve the same.

{{@index_1}}

Give it a try.

WitVault
  • 23,445
  • 19
  • 103
  • 133
  • 2
    `{{@index_1}}` doesn't work and i could not find it documented anywhere. Can you please guide me to its documentation? – Parth Apr 16 '18 at 11:27
  • Is this `{{@index_1}}` actually a thing from Handlebars? It won't work and I can't find documentation for it anywhere. – Float07 Jan 31 '22 at 18:17
4

In Handlebars, you can access the current loop's index like this:

{{#each array}}
  {{@index}}: {{this}}
{{/each}}

Where {{@index}} will evaluate to the current iteration. Eg: 0, 1, 2, etc.

You can find further documentation here: http://handlebarsjs.com/builtin_helpers.html#iteration

Hope it helps.

Javier La Banca
  • 329
  • 4
  • 6