Handlebars Overview | Yext Hitchhikers Platform
What You’ll Learn
In this section, you will learn:
- Basic structure of Handlebars expressions
- How to construct comments in Handlebars
What is Handlebars?
Handlebars is a templating language. This means it takes data, in the form of JSON, and combines it with a template to generate an output file. Think of it like a mail merge – you have a templated letter and you combine that with personalized information to generate your unique emails or letters to all of your customers. Handlebars templates look like normal text with “Handlebars Expressions” embedded in them.
Example Handlebars template:
<p>This is the hitchhiker profile of {{firstName}} {{lastName}}.</p>
Handlebars templates can be used to generate any type of file, like HTML, JavaScript, Markdown, or plain text. In order to use Handlebars templates, you need to install the Handlebars package - thankfully, you’ll be working with repositories (aka, Search sites) that already have Handlebars installed.
Handlebars Expressions
Handlebars Expressions are the text that is surrounded by two opening curly braces {{
and two closing curly braces }}
. When the Handlebars template is executed, the expressions are replaced with values from the input data.
{{firstName}}
and {{ firstName }}
will function the same.
Simple Expressions
First, we’ll start with some JSON data as our input:
{
"firstName": "Bryan",
"lastName": "Landen"
}
Then we’ll write a Handlebars template to show the data from the JSON input in HTML:
<h1>Hitchhiker Profile</h1>
<ul>
<li>First name: {{firstName}}</li>
<li>Last name: {{lastName}}</li>
</ul>
Result
<h1>Hitchhiker Profile</h1>
<ul>
<li>First name: Bryan</li>
<li>Last name: Landen</li>
</ul>
Notice that the expressions - things surrounded with two curly braces - were replaced with the input data.
Comments
Comments are helpful in templates because they can provide supplemental information like context or usage to the Developer or Admin without it appearing in the output file that is seen by the end users.
Template
<!-- This is an HTML comment that will appear in the final output -->
{{! This comment will not appear in the output }}
{{!--
This comment can include Handlebars language constructs, making it perfect for commenting out undesired sections of the template
<h1>{{firstName}}'s Favorites</h1>
<table>
<tr>
<td>Food</td>
<td>{{favorites.food}}</td>
</tr>
<tr>
<td>Color</td>
<td>{{favorites.color}}</td>
</tr>
</table>
--}}
Result
<!-- This is an HTML comment that will appear in the final output -->