Search code examples
node.jshandlebars.jsexpress-handlebarshandlebarshelper

How to pass unique incremental value every time when partial is called from the handlebar template


I am using HandleBar Templates. I have a partial called "table". I am using this "partial" multiple time in my template to generate the dynamic table and rows.

I want to have a unique index for each row for each table. @index will not helpful as I need a unique key for other tables as well. For example:

Table 1

Index Name
----------
1     ABC
2     XYZ


Table 2
--------
Index Name
3     ABC
4     XYZ`


{{> table tableData=table1 cardinal=1}}

{{> table tableData=table2 cardinal=1}}
 

I tried incrementing the variable using this helper but it's value is not available to the next table.

Handlebars.registerHelper("increment", function (value) {
     return parseInt(value) + 1;
});

Hope this makes sense!


Solution

  • Your increment helper would suffice if you omitted the value parameter. The parameter is forcing your partials to know what the start number should be, but this is exactly the problem that has led you to create the helper - that your partials do not know the start number.

    If you create a single variable to hold the increment count and have the helper increment this value and return it each time it is called, this will work just fine. The helper becomes:

    let count = 0;
    Handlebars.registerHelper("increment", function () {
         return ++count;
    });
    

    And it would be called from a template or partial simply like: {{ increment }}.

    I have created a fiddle for reference.