Skip to main content

Handlebars

Handlebars is a simple templating language that allows you to embed expressions in HTML. It is a superset of Mustache, which is another templating language. Handlebars.js is a popular templating engine that is powerful, simple to use, and has a large community.

More information about Handlebars can be found on the Handlebars website (handlebarsjs.com).

Available Handlebars

The following table lists the available Handlebars helpers in the Widget Builder providing a brief description and categorization.
Follow the links to the detailed documentation for each helper or use the sidebar on the right to navigate to the specific helper.

HelperDescriptionCategory
eqStrict equality ===Conditional
eqwEquality ==Conditional
neqStrict inequality !==Conditional
neqwInequality !=Conditional
ltLess than <Conditional
lteLess than or equal <=Conditional
gtGreater than >Conditional
gteGreater than or equal >=Conditional
notNot !Conditional
ifxImitates conditional operator ?:Conditional
emptyCheck if an array is emptyConditional
countLength of an arrayConditional
andLogical AND operationConditional
orLogical OR operationConditional
coalesceReturns first non-falsy value from list of parametersConditional
includesCheck for a value inside an arrayConditional
excerptExtract a sub-string from a stringString
sanitizeSanitize a string to url friendly dash/kebab caseString
newLineToBrReplace new line with line breaks <br> of a stringString
capitalizeEachCapitalize the first letter of each word in a stringString
capitalizeFirstCapitalize the first letter of a stringString
sprintfString produced according to the formatting formatString
lowercaseString to lowercaseString
uppercaseString to uppercaseString
firstFirst element of an arrayString
lastLast element of an arrayString
concatConcatenate two or more stringsString
joinJoin elements of an array using a delimeterString
substringExtract a sub-string from a stringString
sumSum of two numbersMath
differenceDifference of two numbersMath
multiplicationMultiplication of two numbersMath
divisionDivision of two numbersMath
remainderRemainder of two numbersMath
ceilRound a number upward to its nearest integerMath
floorRound a number downward to its nearest integerMath
absFind the absolute value of a numberMath
randomGenerate random number (int/float)Math
formatDateFormat date to specified formatDateTime
datetimeManipulate and format dates and timesDateTime
showIfShow HTML element if expression is trueHTML
hideIfHide HTML element if expression is trueHTML
selectedIfSelect <option> if expression is trueHTML
checkedIfCheck the <input> checkbox if expression is trueHTML
optionsGenerate <option> list for <select>HTML
formatCurrencyFormat currency value according to countryFormatter
jsonConvert object to JSON stringUtility
encodeEncode a string to URI formatUtility
staffbaseIdTokenGet the Staffbase ID tokenUtility
staffbaseAccessTokenGet the Staffbase access tokenUtility
decode_jwtDecode a JWT token into an objectUtility
extract_jwtExtract a specific attribute from a JWT tokenUtility

Conditional

eq

Determine whether or not two values are equal (===).

Parameters

value1 [any] First value to be compared with second. (Required)
value2 [any] Second value to be compared with first. (Required)

Returns

boolean

Usage

{{eq '3' 3}}    => false
{{#if (eq foo "bar")}}
Hello
{{/if}}

eqw

Determine whether or not two values are equal (==) i.e. weak checking.

Parameters

value1 [any] First value to be compared with second. (Required)
value2 [any] Second value to be compared with first. (Required)

Returns

boolean

Usage

{{eqw '3' 3}}   => true
{{#if (eqw foo "bar")}}
Hello
{{/if}}

neq

Determine whether or not two values are not equal (!==).

Parameters

value1 [any] First value to be compared with second. (Required)
value2 [any] Second value to be compared with first. (Required)

Returns

boolean

Usage

{{neq 4 3}}    => true
{{#if (neq foo "bar")}}
Hello
{{/if}}

neqw

Determine whether or not two values are not equal (!=) weak checking.

Parameters

value1 [any] First value to be compared with second. (Required)
value2 [any] Second value to be compared with first. (Required)

Returns

boolean

Usage

{{neqw '3' 3}}    => false
{{#if (neqw foo "bar")}}
Hello
{{/if}}

lt

Check for less than condition (a < b).

Parameters

value1 [any] First value to be compared with second. (Required)
value2 [any] Second value to be compared with first. (Required)

Returns

boolean

Usage

{{lt 2 3}}   => true
{{#if (lt 2 5)}}
Hello
{{/if}}

lte

Check for less than or equals condition (a <= b).

Parameters

value1 [any] First value to be compared with second. (Required)
value2 [any] Second value to be compared with first. (Required)

Returns

boolean

Usage

{{lte 2 3}}   => true
{{#if (lte 5 6)}}
Hello
{{/if}}

gt

Check for greater than condition (a > b).

Parameters

value1 [any] First value to be compared with second. (Required)
value2 [any] Second value to be compared with first. (Required)

Returns

boolean

Usage

{{gt 2 3}}   => false
{{#if (gt 10 7)}}
Hello
{{/if}}

gte

Check for greater than or equals condition (a >= b).

Parameters

value1 [any] First value to be compared with second. (Required)
value2 [any] Second value to be compared with first. (Required)

Returns

boolean

Usage

{{gte 3 3}}   => true
{{#if (gte 10 2)}}
Hello
{{/if}}

not

Logical NOT of any expression. Equivalent to ! operator.

Parameters

expression [any] Any expression.

Returns

boolean

Usage

{{not true}}    => false
{{not false}} => true
{{#if (not (eq foo "bar"))}}
Hello
{{/if}}

ifx

Helper to imitate the ternary conditional operator ? :. E.g. 5 > 7 ? 'foo' : 'bar'.

Parameters

condition [boolean] Satisfying condition for getting first value. Either true of false. (Required)
value1 [any] First value to be displayed as result. (Required)
value2 [any] Second value to be displayed as result. Defaults to an empty string (Optional)

Returns

any

Usage

{{ifx true 'Foo' 'Bar'}}        => Foo  // return (true) ? 'Foo' : 'Bar'
{{ifx false 'Foo' 'Bar'}} => Foo // return (false) ? 'Foo' : 'Bar'
{{ifx (eq value 1) 5 6}} => 6 // return (value === 1) ? 5 : 6
{{ifx (not (eq value 1)) 5 6}} => 6 // return (value !== 1) ? 5 : 6

<!-- The third parameter is optional, and by default it will be blank string ('') -->
{{ifx true 'active'}} => 'active'
{{ifx false 'active'}} => ''
{{ifx (eq foo "bar") "Hello" "World"}}

empty

Check if an array is empty.

Parameters

array [array] Array/object to be checked. (Required)

Returns

boolean

Usage

var array = [5, 6];     // An array.
{{empty array}} => false
{{#if (empty array)}}
Hello
{{/if}}

count

Determine the length of an array. Equivalent to array.length operator in JavaScript.

Parameters

array [array] Array whose elements to be counted. (Required)

Returns

number|false

Usage

var array = [5, 6];    // An array.
{{count array}} => 2;

and

Returns the logical AND of two or more parameters passed i.e it is true iff all the parameters are true.

Parameters

params [any] Any number of boolean parameters. (Required)

Returns

boolean

Usage

var value1 = value2 = true;
{{and value1 value2}} => true

var value1 = false, value2 = true;
{{and value1 value2}} => false
{{#if (and value1 value2)}}
<!-- do something -->
{{else}}
<!-- do something else -->
{{/if}}

or

Returns the logical OR of two or more parameters passed i.e it is true if any of the parameters is true.

Parameters

params [any] Any number of boolean parameters. (Required)

Returns

boolean

Usage

var value1 = true, value2 = false;
{{or value1 value2}} => true

var value = value2 = false;
{{or value1 value2}} => false
{{#if (or value1 value2)}}
<!-- do something -->
{{else}}
<!-- do something else -->
{{/if}}

coalesce

Returns the first non-falsy value from the parameter list. Works quite similar to the SQL's COALESCE() function, but unlike this checks for the first non-false parameter.

Parameters

params [any] Any number of parameters. (Required)

Returns

any

Usage

var fullName = 'Foo Bar', nickName = 'foob';
{{coalesce fullName nickName 'Unknown'}} => 'Foo Bar'

var fullName = '', nickName = 'foob';
{{coalesce fullName nickName 'Unknown'}} => 'foob'

includes

Returns true if an array includes a value. It checks for the existence of the value in array strictly (value + data type) by default. Can check non-strictly (value only) by sending third argument as false.

Parameters

params [array] The array. (Required)
params [any] The value to be checked for existence in the array. (Required)
params [boolean] FALSE for non-strict checking. TRUE by default. (Optional)

Returns

boolean

Usage

var array = [1, 2, 3];
var value = 2;

{{includes array value}} => true

var value = '2'
{{includes array value}} => false
{{includes array value true}} => false
{{includes array value false}} => true
{{#if (includes array value)}}
<!-- do something -->
{{/if}}

{{ifx (includes array value) "Yes" "No"}}

String

excerpt

Extract a sub-string from a string.

Parameters

string [string] The string from which characters are to be extracted. (Required)
length [number | string] Number of characters to be extracted from string. Default value is 50. (Optional)

Returns

string

Usage

{{excerpt 'Just Wow' 4}} => 'Just...'

sanitize

Converts a string to URL friendly dash-case string removing special characters.

Parameters

string [string] The string to be converted to URL. (Required)

Returns

string

Usage

{{sanitize 'JuSt #Wow'}} => 'just-wow'

newLineToBr

Replace \n with <br> tags.

Parameters

string [string] The string that needs replacement of \n by <br> tags. (Required)

Returns

string

Usage

{{{newLineToBr 'newLineToBr helper \n is very \n useful.'}}}    => newLineToBr helper <br> is very <br> useful.

capitalizeEach

Capitalize the first letter of each word in a string.

Parameters

string [string] The sentence/string to be capitalized. (Required)

Returns

string

Usage

{{capitalizeEach 'just wow'}} => 'Just Wow'

capitalizeFirst

Capitalize the first letter of a string.

Parameters

string [string] The sentence/string to be capitalized. (Required)

Returns

string

Usage

{{capitalizeFirst 'just wow'}} => 'Just wow'

sprintf

sprintf helper sends formatted data as string output.

Parameters

format [string] The message/string that uses different formats of variables. (Required)
args [arbitrary arguments] Any number of parameters/values. (Required)

Returns string

Usage

{{sprintf "%s %s!" "Hello" "Kabir"}}                      => 'Hello Kabir!'
{{sprintf "%s %s %d %s %d" "Foo" "Bar" 55 "Baz" "20"}} => 'Foo Bar 55 Baz 20'
var obj = { greeting: 'Hello', name: 'Mandy' };
{{sprintf "%(greeting)s %(name)s! How are you?" obj}}
{{sprintf "%(greeting)s %(name)s! " greeting="Hello" name="Mandy"}}

lowercase

Changes the string to lowercase.

Parameters

param [string] The string to be converted to lower case. (Required)

Returns

string

Usage

{{lowercase 'JUST WOW!!!'}} => 'just wow!!!'

uppercase

Changes the string to uppercase.

Parameters

param [string] The string to be converted to upper case. (Required)

Returns

string

Usage

{{uppercase 'just wow!!!'}} => 'JUST WOW!!!'

first

Get the first element of a collection/array.

Parameters

collection [array] The collection/array of objects(strings, integers). (Required)

Returns

string

Usage

someArray = ['David', 'Miller', 'Jones'];
{{first someArray}} => 'David'

last

Get the last element of a collection/array.

Parameters

collection [array] The collection/array of objects(strings, integers). (Required)

Returns

string

Usage

someArray = ['David', 'Miller', 'Jones'];
{{last someArray}} => 'Jones'

concat

Concat two or more strings.

Parameters

params [arguments] Any number of arguments. (Required)

Returns

string

Usage

{{concat 'Hello' ' world' '!!!'}} => 'Hello world!!!'

join

Join the elements of an array using a delimeter.

Parameters

array [array] An array of elements to be joined. (Required)
delimeter [string] The delimeter using which the elements of array are to be joined. (Required)

Returns

string

Usage

someArray = ['Hands', 'legs', 'feet'];
{{join someArray ' & '}} => 'Hands & legs & feet'

substring

Extract a sub-string from a string.

Parameters

string [string] The string from which characters are to be extracted. (Required)
start [number | string] The position from where the extraction starts. (Required)
end [number | string] The position where the extraction ends. (Optional)

Returns

string

Usage

{{substring 'Just Wow' 4 7}}      => 'Wow'
{{substring 'Hello World' -5}} => 'World'

Math

sum

A sum helper calculating the sum of two numbers.

Parameters

value1 [number | string] First number. (Required)
value2 [number | string] Second number. (Required)

Returns

number

Usage

{{sum 1 2}}     => 3
{{sum 5.6 6.7}} => 12.3

difference

A difference helper calculating the difference of two numbers.

Parameters

value1 [number | string] First number. (Required)
value2 [number | string] Second number. (Required)

Returns

number

Usage

{{difference 5 2}}      => 3
{{difference 7.2 3.4}} => 3.8

multiplication

A multiplication helper calculating the multiplication of two numbers.

Parameters

value1 [number | string] First number. (Required)
value2 [number | string] Second number. (Required)

Returns

number

Usage

{{multiplication 5 2}}      => 10
{{multiplication 5.2 6.4}} => 33.28

division

A division helper calculating the division of two numbers.

Parameters

value1 [number | string] First number. (Required)
value2 [number | string] Second number. (Required)

Returns

number

Usage

{{division 4 2}}      => 2
{{division 5.2 1.6}} => 3.25

remainder

A remainder helper calculating the remainder of two numbers.

Parameters

value1 [number | string] First number. (Required)
value2 [number | string] Second number. (Required)

Returns

number

Usage

{{remainder 5 3}}      => 2
{{remainder 5.2 2.5}} => 0.20000000000000018

ceil

A ceil helper to find the ceil value of the number. Equivalent to Math.ceil() in JavaScript.

Parameters

value [number | string] Number to be rounded to nearest greater integer. (Required)

Returns

integer

Usage

{{ceil 5.6}}    => 6

floor

A floor helper to find the floor value of the number. Equivalent to Math.floor() in JavaScript.

Parameters

value [number | string] Number to be rounded to nearest lower integer. (Required)

Returns

integer

Usage

{{floor 5.6}}   => 5

abs

An abs helper to find the absolute value of the number. Equivalent to Math.abs() in JavaScript.

Parameters

value [number | string] Number to perform absolute value operation on. (Required)

Returns

number

Usage

{{abs -5.6}}   => 5.6

random

The random helper generates a random number between min and max. Possible as integer or as float with maximal 2 decimals.

Parameters

min [number] Default is 1. Minimum value (inclusive) (Optional)
max [number] Default is 100. Maximum value (inclusive) (Optional)
type [string] 'int' for integer, 'float' for float (max 2 decimals). Default is integer (Optional)

Returns

number

Usage

{{random}}                => integer between 1 and 100
{{random 5 10}} => integer between 5 and 10
{{random 1 10 'float'}} => float between 1 and 10, max 2 decimals

DateTime

formatDate

A formatDate helper to format date using the toFormat function with formatting tokens from Luxon.

tip

Better use the datetime helper for more versatile date-time functionalities.

To know more about the formatting tokens, you can visit the Luxon "Table of tokens" section.
https://moment.github.io/luxon/#/formatting?id=table-of-tokens

You can find more information about the Luxon "toFormat" function here.
https://moment.github.io/luxon/#/formatting?id=toformat

Parameters

formatString [string] Format string based on Luxon "toFormat" function (Required)
date [date] The date/date-time that needs to be formatted using the input pattern "yyyy-MM-dd" (Optional)
localeString [string] ISO 3166-1 locale code represented in https://en.wikipedia.org/wiki/ISO_3166-1#Codes (Optional)

Returns

string

Usage

{{formatDate 'yyyy-MM-dd' date}}                       => 2024-06-24 (using the current date)
{{formatDate 'MM/dd/yyyy' '2016-01-22'}} => 01/22/2016
{{formatDate 'MMMM dd, yyyy GG' '2016-01-22' 'en'}} => 'January 22, 2016 Anno Domini'
note

The date formatting parameters are partially based on Luxon (moment.github.io/luxon).


datetime

The datetime helper is a versatile Handlebars helper for manipulating and formatting dates and times. It uses various initialization methods, modification operations, and finalization options to provide a wide range of date-time functionalities.

Parameters

  • Initialization: You can initialize the date using various methods.

    • from_var: Initializes from a JavaScript date object string.
    • from_timestamp: Initializes from a timestamp in milliseconds.
    • from_millis: Initializes from a timestamp in milliseconds.
    • from_rfc2822: Initializes from an RFC2822 formatted string.
    • from_iso: Initializes from an ISO formatted string.
    • from_str: Initializes from a custom formatted string using input_format.
    • No parameters: Uses the current date and time.
  • Modification: You can modify the initialized date using the following options.

    • with_year: Sets the year.
    • with_month: Sets the month.
    • with_day: Sets the day.
    • with_hour: Sets the hour.
    • with_minute: Sets the minute.
    • with_second: Sets the second.
    • add_years: Adds the specified number of years.
    • add_months: Adds the specified number of months.
    • add_weeks: Adds the specified number of weeks.
    • add_days: Adds the specified number of days.
    • add_hours: Adds the specified number of hours.
    • add_minutes: Adds the specified number of minutes.
    • add_seconds: Adds the specified number of seconds.
    • sub_years: Subtracts the specified number of years.
    • sub_months: Subtracts the specified number of months.
    • sub_weeks: Subtracts the specified number of weeks.
    • sub_days: Subtracts the specified number of days.
    • sub_hours: Subtracts the specified number of hours.
    • sub_minutes: Subtracts the specified number of minutes.
    • sub_seconds: Subtracts the specified number of seconds.
  • Timezone & Locale: You can specify the timezone and locale.

    • with_timezone: Sets the timezone.
    • with_locale: Sets the locale.
  • Finalization: You can finalize the date using various formatting and conversion options.

    • to_rfc2822: Converts to RFC2822 format.
    • to_isodate: Converts to ISO date format (yyyy-MM-dd).
    • to_isotime: Converts to ISO time format (HH:mm:ss.SSSZ).
    • to_timestamp: Converts to a Unix timestamp in milliseconds.
    • to_seconds: Converts to Unix timestamp in seconds.
    • to_utc: Converts to UTC timestamp in milliseconds.
    • to_localestring: Converts to a locale string format. Optionally, you can specify the locale format.
    • to_relative: Converts to a relative time format.
    • to_relative_units: Converts to a relative time format with specified units.
    • to_relative_calendar: Converts to a relative calendar format.

Returns

string

Usage

{{datetime from_var="Fri May 19 2021 10:00:00 GMT+0200"}}                    => "2021-05-19T10:00:00.000+02:00"
{{datetime from_timestamp="1621411200000"}} => "2021-05-19T10:00:00.000+02:00"
{{datetime from_iso="2021-05-19"}} => "2021-05-19T00:00:00.000+02:00"
{{datetime from_str="2021-05-19" input_format="yyyy-MM-dd"}} => "2021-05-19T00:00:00.000+02:00"
{{datetime add_days="2"}} => "2021-05-21T00:00:00.000+02:00"
{{datetime with_timezone="America/New_York"}} => "2021-05-18T18:00:00.000-04:00"
{{datetime to_rfc2822=true}} => "Wed, 19 May 2021 08:00:00 +0000"
{{datetime to_localestring=true with_locale="en-us"}} => "5/19/2021"
{{datetime to_relative=true from_str="2011-02-03" input_format="yyyy-MM-dd" with_locale="fr"}} => "il y a 10 ans"

HTML

showIf

A showIf helper for showing any HTML element.

Parameters

expression [boolean] Condition to be checked. (Required)

Returns

string

Usage

{{showIf true}}     => ''
{{showIf false}} => 'hidden'

hideIf

A hideIf helper for hiding any HTML element.

Parameters

expression [boolean] Condition to be checked. (Required)

Returns

string

Usage

{{hideIf true}}     => 'hidden'
{{hideIf false}} => ''

selectedIf

A selectedIf helper for dropdown and radio boxes.

Parameters

expression [boolean] Condition to be checked. (Required)

Returns

string

Usage

{{selectedIf true}}     => 'selected'

checkedIf

A checkedIf helper for checkboxes.

Parameters

expression [boolean] Condition to be checked. (Required)

Returns

string

Usage

{{checkedIf true}}      => 'checked'

options

An options helper for generating <option> list for <select> dropdowns.

Parameters

data [array] List of data (Required)
id [string] Name of identifier key from the data list, defaults to id (Optional)
text [string] Name of description key from the data list, defaults to description (Optional)
selected [string] Id to be set as selected (Optional)

Returns

string | HTML

Usage

{{{options data}}}
{{{options data selected="value"}}}
{{{options data id="id" text="description"}}}

A simple example:

const data = [
{
id: 1,
description: 'Foo'
},
{
id: 2,
description: 'Bar'
},
{
id: 3,
description: 'Foo Bar'
}
];
{{{options data selected="2"}}}

will generate HTML:

<option value="1">Foo</option>
<option value="2" selected>Bar</option>
<option value="3">Foo Bar</option>

You can also override the default key names for id & description using the id & text options in the helper.

const data = [
{
value: 1,
text: 'New York'
},
{
value: 2,
text: 'London'
}
];
{{{options data selected="1" id="value" text="text"}}}

will generate HTML:

<option value="1" selected>New York</option>
<option value="2">London</option>

Formatter

formatCurrency

Format the currency value according to country code and locale.

Parameters

value [number] The numerical value of currency. (Required)
args [arbitrary arguments] The currency formatting parameters. (Optional)

Returns

string

Usage

{{formatCurrency 1234567.86 code='INR'}}                                                                  => ₹ 12,34,567.86
{{formatCurrency 1234567.86 code='EUR' locale='fr'}} => 1 234 567,86 €
{{formatCurrency 1234567.86 code='USD' decimal=',' group='.' symbol='&dollar; (USD)' pattern="#.# !"}} => 1234567,9 $ (USD)
note

The currency formatting parameters are used from CurrencyFormatter.js (osrec.github.io/currencyFormatter.js).


Utility

json

The json helper converts the given data to a JSON string or parses a JSON string to an object.

Parameters

  • data: The data to be converted to a JSON string.
  • parse: If true, the JSON string will be parsed to an object.
  • pretty: If true, the JSON string will be formatted with spaces and line breaks.

Returns

string

Usage

{{json data}}                => '{"name":"John","age":30}'
{{json data parse=true}} => { name: 'John', age: 30 }
{{json data pretty=true}} => '{
"name": "John",
"age": 30
}'
var data = { name: 'John', age: 30 };
{{json data}}

slice

The slice helper returns a slice of the given array.

Parameters

  • data: The array from which the slice is to be taken.
  • start: The index at which to begin the slice.
  • end: The index at which to end the slice.

Returns

array | string

Usage

var someArray = ['David', 'Miller', 'Jones'];
{{slice someArray 1}} => ['Miller', 'Jones']
{{slice someArray 0 1}} => 'David'

encode

The encode helper converts the given string to a URI-encoded string.

Parameters

  • data: The string to be URI-encoded.

Returns

string

Usage

{{encode data}}    => 'Hello%20World%21'
{{encode "Hello World!"}}

staffbaseIdToken

The staffbaseIdToken helper returns the Staffbase ID token as a string.

Parameters

None

Returns

string

Usage

{{staffbaseIdToken}}    => "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
<div data-token="{{staffbaseIdToken}}"></div>

staffbaseAccessToken

The staffbaseAccessToken helper returns the Staffbase access token as a string.

Parameters

None

Returns

string

Usage

{{staffbaseAccessToken}}    => "ory_ae4b742ea3..."
<div data-token="{{staffbaseAccessToken}}"></div>

decode_jwt

The decode_jwt helper decodes a JSON Web Token (JWT) and returns its payload as an object.

Parameters

token [string] The JWT token to be decoded. (Required)

Returns

object

Usage

{{decode_jwt "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."}}
=> { sub: "1234567890", name: "John Doe", iat: 1516239022 }
{{#with (decode_jwt staffbaseIdToken)}}
<div>User ID: {{sub}}</div>
<div>User Name: {{name}}</div>
<div>Issued At: {{iat}}</div>
{{/with}}

extract_jwt

The extract_jwt helper extracts a specific attribute from a decoded JWT token.

Parameters

token [string] The JWT token to extract data from. (Required)
attribute [string] The name of the attribute to extract from the token. (Required)

Returns

string

Usage

{{extract_jwt "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." "name"}}    => "John Doe"
<div>User ID: {{extract_jwt staffbaseIdToken "sub"}}</div>