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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With