Handlebars helper: {{counter}}

For documents such as labels and raffle tickets, it’s often necessary to generate sequential numbers or counters that update for each record in your dataset. This tutorial demonstrates how to easily integrate a pre-built Handlebars helper to accomplish this task.

Note: The topic discussed in this article will become a standard option in OL Connect version 2024.2. However, the article still provides valuable information on creating a custom Handlebars helper.

Setting Up the Custom Counter Helper

To add the custom counter helper to your template:

  1. Open OL Connect Designer and create a Control Script in the Scripts panel. You can give this script any name, for example: Counter Helper
  2. Copy the code below and paste it to the script editor window.
  3. Click OK to save the script.

The script defines the counter helper which you can now use in your template. The counter is based on the specified options: start (star value), step (step size), pad (number of characters used to pad the result), padChar (the string used for padding, by default this is “0” aka leading zeros).

Handlebars.registerHelper('counter', function(options) {

    // Options hash containing named variables

    // Default start value is 1 if not provided
    const start   = options.hash.start !== undefined ? options.hash.start : 1; 
    const step    = options.hash.step || 1; // Default step value is 1
    const pad     = options.hash.pad || 0; // Default pad length is 0
    const padChar = options.hash.padChar || '0'; // Default pad character is '0'
    
    // Calculate the counter value based on start, step, and record.index
    let counterValue;

 	if (start !== undefined) {
        counterValue = start + ((record.index - 1) * step);
    } else {
        counterValue = 1 + (record.index - 1) * step;
    }
    
    // Add padding
    if ( pad !== undefined && pad > 0) {
        counterValue = counterValue.toString().padStart(pad, padChar);
    }
    
    return counterValue;
    
});

Usage samples

Here are some basic examples demonstrating how to use the counter helper in your OL Connect Designer template:

Custom start and step

{{counter start=10 step=5}}

Outputs the counter starting from 10 with increments of 5 for each record.

Padded counter

{{counter pad=4}}

Outputs the counter starting from 1 and pads the number to 4 digits with leading zeros (e.g., 0001, 0002, …).

Pad counter with custom character

{{counter pad=4 padChar="_"}}

Outputs the counter starting from 1 and pads the number to 4 digits with the specified character (e.g., ___1, ___2, …).