Skip to main content

Helpers

Helpers are functions that you can use to perform logic, manipulate data or format text directly within your template. By default, Handlebars is “logic-less” (it avoids putting complex logic inside templates), but helpers give you a controlled way to add logic when needed.

In other words, a helper is just a function you call from inside a template.

{{helperName arg1 arg2}}

There are two types of helpers:

Inline helpers​

Return a value directly

Example:

template.hbs

<p>{{uppercase 'abc'}}</p> // ABC

Block helpers​

Control a block of template content using {{#...}}...{{/...}}

As you can we in the above example, we use #each helper to control how project name and company name are rendered in a list. The each helper will loop each item in an array of data, then we refer each item by using this keywork, and then we just need to call out base on the data properties for getting values.

userProjects.hbs

<ul>
{{#each projects}}
<li>{{this.projectName}} - {{this.company}}</li>
{{/each}}
</ul>

In Handlebars, we have:

  • Built-in helpers: #if, #each, #with, #unless, etc. You can check the Helpers Specification for all the built-in helpers.
  • Custom helpers: your own helpers that are implemented by using JavaScript.

Creating custom helpers​

Custom helpers allow you to extend the engine to suit your specific application needs.

To make your helpers can be run in our system, you have to follow this function signature when implementing them:

functionName.js

function functionName(context, options) {
...
}

where:

  • context: first input parameter
  • options: an object give you access to paramters, hash arguments

Inside options object, you can access to two properties:

  • params: an object contains all params except the first one. (The first param is the context)
  • hash: a key-value collection allows user access the input parameters
warning

The name of a file must be exact the same with the name of the function.

Usage:

{{js:functionName args}}

Example:

Assume we have data like below:

{
"items": [
{
"key": "color",
"label": "green",
"content": "001"
},
{
"key": "url",
"content": "www.example.com"
},
{
"key": "version",
"content": "1.0.0"
}
]
}

We want a helper that can find item base on key property and then return value of required property (content or label). So we need to implement a helper which will receive 3 params:

  • data: the input data
  • key: value of key property of the item we want to extract
  • propertyName: the name of property in the item we want to get its value

Here is the implementation of the helper file that uses options.params to access paramters

getItemValue.js

function getItemValue(context, options) {
const inputData = context;
const params = options.params || [];
const key = params[0];
const propertyName = params[1];

// Check valid paramenters
if (!Array.isArray(inputData) || inputData.length === 0) return '';
if (key === null || key === '') return '';
if (propertyName === null || propertyName === '') return '';

// Find expected item
const found = inputData.find((x) => x && x.key === key);
if (found) {
return found[propertyName] ?? '';
}
return '';
}

Usage:

<div>
<p>{{js:getItemValue items 'color' 'label'}}
-
{{js:getItemValue items 'color' 'content'}}</p>

<a
href='{{js:getItemValue items "url" "content"}}'
target='_blank'
>Website</a>
<p>Version: {{js:getItemValue items 'version' 'content'}}</p>
</div>

If you want to use options.hash, the implement should be like this:

function getItemValue(context, options) {
const inputData = context;
const key = options.hash('key', 'defaultValue');
const propertyName = options.hash('propertyName', 'defaultValue');

// Check valid paramenters
if (!Array.isArray(inputData) || inputData.length === 0) return '';
if (key === null || key === '') return '';
if (propertyName === null || propertyName === '') return '';

// Find expected item
const found = inputData.find((x) => x && x.key === key);
if (found) {
return found[propertyName] ?? '';
}
return '';
}

and when use the helper, you have to explicit use the parameter name when pass value

<div>
<p>{{js:getItemValue items key='color' propertyName='label'}}
-
{{js:getItemValue items key='color' propertyName='content'}}</p>

<a
href='{{js:getItemValue items key='url' propertyName='content'}}'
target='_blank'
>Website</a>
<p>Version: {{js:getItemValue items key='version' propertyName='content'}}</p>
</div>

HTML output:

<div>
<p>green - 001</p>
<a href="www.example.com">Website</a>
<p>Version: 1.0.0</p>
</div>

Short Helper Reference​

The following table lists all the helpers that are available in the priint Handlebars implementation. For more details and examples see the comprehensive Helper documentation.

ExampleDescription
Content Injection
{{prop}}Simple expression. Will output the value for the key prop into the HTML.
{{{prop}}}Escaping: A triple mustache forces the system to supress HTML escaping.
{{'astring'}}Output a literal string. Producing astring.
{{123.45}}Output a literal number 123.45 without further formatting.
{{this}}Inject the current context (this) as string.
{{.}}Same as this. Output the current context as string.
{{prop.title }}Nested contexts. Use . paths to access nested contexts
{{prop.[title] }}Alternative for nested contexts.
{{../prop.name }}Navigating one level up in the data. Use ../ paths to access parent contexts
{{prop.img.[2]}}List elements. Use [] to access a list element.
\{{ prop }}Escaping the mustache. Use \ for escaping. Will output {{ prop }} into the HTML.
General Helper Syntax
{{hlpr prop}}Apply the inline helper function hlpr to the value of propand inject its result into the output.
{{hlpr prop1 prop2}}Helpers may accept more than one argument
{{hlpr prop1 mode='foo' mode2=prop2}}Helpers may accept 'hash' arguments (i.e., named arguments). Values of hash arguments can be literal strings, numbers or expressions themself.
{{#hlpr}}...{{/hlpr}}Block helpers start with a # hash character.
{{#hlpr}}...{{else}}...{{/hlpr}}Block helpers allow if-then-else constructs.
{{! code comments }}Comment for handlebars. Will not be part of the HTML.
{{> templateName}}Partial block. Calling a 'sub-template'
{{hlpr1 (hlpr2 (hlpr3 prop))}}Subexpressions are supported. Subexpressions are embraced byn brackets as a whole.
Standard Block Helpers
{{#if prop}}...{{else}}...{{/if}}A block will be rendered if prop evaluates to true.
{{#unless prop}}...{{else}}...{{/unless}}A block will be rendered if prop does not evaluate to true.
{{#each prop}}...{{/each}}Iterate over a list of items in prop.
{{#with prop}}...{{/with}}Changes the evaluation context of a template-part to prop.
{{#block}}...{{/block}}Template Inheritance. See https://jknack.github.io/handlebars.java/reuse.html
{{#partial}}...{{/partial}}Template Inheritance. See https://jknack.github.io/handlebars.java/reuse.html
Conditionals
{{#and prop1 prop2}}...{{else}}...{{/and}}True if all arguments are evaluated to true.
{{#contains str1 str2}}...{{else}}...{{/contains}}True if string str2 is contained in string str2.
{{#endsWith str1 str2}}...{{else}}...{{/endsWith}}True if string str1 ends with string str2.
{{#eq prop1 prop2}}...{{else}}...{{/eq}}True if prop1 equals prop2.
{{#gt prop1 prop2}}...{{else}}...{{/gt}}True if prop1 is greater compared to prop2.
{{#gte prop1 prop2}}...{{else}}...{{/gte}}True if prop1 is greater or equal compared to prop2.
{{#lt prop1 prop2}}...{{else}}...{{/lt}}True if prop1 is littler compared to prop2.
{{#lte prop1 prop2}}...{{else}}...{{/lte}}True if prop1 is littler or equal compared to prop2.
{{#matches str1 str2}}...{{else}}...{{/matches}}True if string str1 matches the regular expression in str2
{{#neq prop1 prop2}}...{{else}}...{{/neq}}True if prop1 is NOT equals compared to prop2.
{{#not prop1}}...{{else}}...{{/not}}True if prop1 evaluated to false.
{{#or prop1 prop2}}...{{else}}...{{/or}}True if none of the arguments evaluates to true.
{{#startsWith str1 str2}}...{{else}}...{{/startsWith}}True if string str1 starts with string str2.
Numbers
{{absolute -123.45}}Get absolute (positive) value of a number 123.45.
{{add 123 0.45 }}Add numbers and produce 123.45.
{{ceiling 123.45 }}Smallest integer that is not less than the argument: 124.
{{divide -123 2}}}Divide numbers and produce 61.5
{{floor 123.45 }}Largest integer that is not greater than the argument: 123
{{modulo 14 3 }}Apply modulo function on the aruments and produce 2
{{multiply -123 2.5}}Multiply numbers and produce -307.5
{{negate -123 }}Negate a number and produce 123.0
{{number '-123' }}Parse a string as a number and produce 123.0
{{power 144 0.5 }}Potentiate numbers and produce 12.0
{{round 123.45 }}Round a number to next nearest integer and produce 123.
{{subtract 5 2}}Subtract numbers and produce 3.0.
Strings
{{abbreviate 'Foo bar!' 6 }}Truncates text to a certain leng. Will produce Foo...!.
{{capitalize 'abc def'}}Capitalizes every whitespace-separated word. Will produce Abc Def.
{{capitalizeFirst 'abc def'}}Capitalizes the first character. Will produce Abc def.
{{center 'abc def'}}Centers text in a field of a given width. Will produce ab.
{{concat 'abc def'}}Returns the concatenation of the arguments. Will produce ab.
{{cut 'abc def'}}Removes all occurrences of a substring. The default substring is a space. Will produce ab.
{{defaultIfEmpty 'abc' 'def'}}If value evaluates to False, uses the given default. Otherwise, uses the value. Will produce abc.
{{join 'a' 'b' 'c' ' - '}}Joins an array, iterator or an iterable with a string. Will produce a - b - c.
{{ljust 'abc' 6 pad='-'}}Left-aligns the value in a field of a given width. Argument: field size. Will produce abc---.
{{lower 'Abc Def'}}Converts text to lowercase. Will produce abc def.
{{normalizeSpace ' abc\t\tdef '}}Removes leading, trailing, and repeating white spaces. Will produce abc def.
{{numberFormat 1234567.8901 '#,###,###,##0.00'}}Formats Java Number values. Will produce 1,234,567.89.
{{rjust 'abc' 6 pad='-'}}Right-aligns the value in a field of a given width. Argument: field size. Will produce ---abc.
{{replace 'AC/DC' '/' '-'}}Replaces all literal occurrences of a target substring. Will produce AC-DC.
{{replaceAll 'AC/DC' '\W' '-'}}Replace strings based on a regular expression. Will produce AC-DC.
{{substring 'abc' 0 2}}Returns a substring by start and optional end index. Will produce ab.
{{substringAfter 'abc' 'b'}}Returns a substring after the first occurance of another string. Will produce c.
{{substringBefore 'abc' 'b'}}Returns a substring before the first occurance of another string. Will produce a.
{{slugify 'Foo Bar'}}Converts text to a simple lowercase slug. This implementation keeps letters and converts whitespace to hyphens. Will produce foo-bar.
{{stringFormat 'Hello %s %s' 'Sue' 'Doe'}}Uses Java String.format as a avriant of sprintf. Will produce Hello Sue Doe.
{{stringLength 'abc def'}}Returns the number of characters in the string. Will produce 7.
{{stripTags '<p>ter</p>'}}Removes HTML/XML tags. Will produce ter. HTML entity encoding will not be affected.
{{translate 'abc def'}}'Translate' a string character by character. Will produce ab.
{{unescapeHtml '&lt;Fran&ccedil;ais&gt;' }}Returns a string with all HTML escaped characters in raw form. Will produce <Français>.
{{upper 'abc def'}}Converts text to uppercase. Will produce ABC DEF.
{{wordWrap 'abc def' 5 }}Wraps text at the requested width. Will produce abc\r\ndef.
{{yesno false yes="Ja" no="Nein" }}Maps boolean/null values to strings. Will produce Nein.
Dates and Times
{{dateFormat}}Format a datetime object. Supports some named formats as well as self-defined patterns.
{{dateTimeFormat}}Parse and format a datetime object from a long or string. Many named formats are supported but also self-defined patterns.
{{dateTimeParse}}Parse a string into a datetime object (actually millis since epoch).
{{now}}Format the current time. Shortcut for {{dateTimeFormat 'now'}}.
Media URLs
{{proxyUrl 'https://example.com/image.png'}}Rewriting a remote URL as MediaProxy URL. Will produce something like http://mediaproxy/a/j48eu/?https://example.com/image.png.
Indexes
{{index "idx" match="$.prop[*]" use="name"}}Define an index. This mimics <xsl:key name="" match="" use=""/>.
{{#indexEach 'idx' val='myName'}}...{{/indexEach}}Iterate over elements from an index idx where the value is myName.
{{#indexWith 'idx' val='myName}}...{{/indexWith}}Switch context to the (first) element from an index idx where the value is myName.
Environment Variables
{{env 'GRID_TICKET'}}Accessing context variables from the call environment.
{{setenv 'MY_KEY' '123'}}Setting context variables in the call environment.
Localization
{{localize 'key' prop1 locale='de-AT'}}Get the locale specific string for key from localization.json and format it using prop1 as arguements.
Misceleanous
{{log 'Oops'}}Write to the tracer.log. Will produce not output.
{{either preferredLabel fallbackLabel "N/A"}}Returns the first non-falsy value among context and params.
{{filter prop 'mykey' 'myval' }}Filter elements in prop for ll elements with an attribute named mykey that have the value myval and return the array of matching elements.
{{generateId this}}Create a document local unique ID for a data context. Will produce something like i41ccb3b91b0b.
{{itemContent this '0815' }}Get the first element where an attribute named key exists and has the value 0815.
{{parse '{"json":"markup"}'}}Parses the input string as JSON array or object or as XML and returns the resulting object.
{{sort prop 'firstname' order='descending'}}Sort elements in prop using the firstname field in descending order.
{{when true "Enabled" "Disabled"}}Ternary operator - using #if as a function. Will produce Enabled. Allows for a regex hash for string comparisons.
{{xpath . "count(prop/imgs)"}}Filtering context data via xpath (using JXPath library). Will return the number of images.
User Defined JavaScript
{{js:funcName prop }}Calling a custom JavaScript helper method with name funcName. The method must be defined in a JavaScipt file in the /js_helpers directory.