Handlebars
Introduction
Handlebars is a simple templating language.
It uses a template and an input object to generate HTML or other text formats. Handlebars templates look like regular text with embedded Handlebars expressions.
<p>{{firstname}} {{lastname}}</p>
A handlebars expression is a {{, some contents, followed by a }}. When the template is executed, these expressions are replaced with values from an input object.
Basic usage
Handlebars expressions are some contents enclosed by double curly braces . In the below template, firstname is a variable that is enclosed by double curly braces, which is said to be an expression.
<p>{{firstname}} {{lastname}}</p>
If the below input object is applied to the template:
{
firstname: "Yehuda",
lastname: "Katz",
}
Expressions are compiled to produce the output as follows:
<p>Yehuda Katz</p>
Path expression
Handlebars expressions can also be dot-separated paths.
<p>{{person.firstname}} {{person.lastname}}</p>
This expression looks up the person property in the input object and in turn looks up the firstname and lastname property within the person object.
Pass the below input object to the template:
{
person: {
firstname: "Yehuda",
lastname: "Katz",
},
}
Output will be generated as below:
Yehuda Katz
HTML-escaping
In Handlebars, the values returned by the {{expression}} are HTML-escaped. Say, if the expression contains &, then the returned HTML-escaped output is generated as &. If you don’t want Handlebars to escape a value, use the “triple-stash”, {{{:
In the below template, you can learn how to produce the HTML escaped and raw output.
raw: {{{specialChars}}}
html-escaped: {{specialChars}}
Pass the special characters to the template:
{ specialChars: "& < > \" ' ` =" }
Expressions enclosed by “triple-stash” ({{{) produce the raw output. Otherwise, HTML-escaped output is generated as below.
raw: & < > " ' ` =
html-escaped: & < > " ' ` =