DO YOU NEED A CONTENT WRITER FOR YOUR BUSINESS?

Your One-Stop Solution for All Content Needs! Click here for more!
Javascript

Getting Started with Handlebars JS

Share

Handlebars js is a popular templating engine which is simple to use, powerful and has a large community based on the Mustache template language.

Using this, you can write cleaner code and separate the generation of HTML from the rest of your JavaScript. Written in JavaScript language, Handlebars JS is a compiler which takes any HTML or Handlebars expression and then compiles them to a JavaScript function.

The 3 main parts of Handlebars JS template are:

  • Handlebars.js Expressions
  • Data (or Context)
  • The Handlebars Compile Function

Installation and Usage

Download the latest build from the GitHub project.

Handlebars is a JavaScript library, so you can include it in your web pages in a same way you would any other script:

// From File

<script type=”text/javascript” src=”handlebars.js” />

// From CDN <script src=”https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js”></script>

1. Templates

The syntax of template is very easy. This contains text and HTML, mixed with Handlebars expressions that is wrapped in double or triple curly braces {{}}. This expressions tell the Handlebars to include the value of variables or to execute helper functions and this templates need to be compiled before using.

HTML:

<script id=”name-template” type=”text/x-handlebars-template”>

<p>Hello {{firstname}} {{lastname}}.</p>

</script>

<div class=”name-placeholder”></div>

JS:

$(function () {

var theTemplateScript = $(“#name-template”).html();

var theTemplate = Handlebars.compile(theTemplateScript);

var context={ “firstname”: “John”, “lastname”: “Doe” };

var theCompiledHtml = theTemplate(context);

$(‘.name-placeholder’).html(theCompiledHtml);

});

OUTPUT:

Hello John Doe.

2. Expressions

Expression is the simplest dynamic element in a Handlebars template i.e. surrounded by handlebars, like {{expression}}. Handlebars escapes all the results of expressions by default, but using a “triple-stash {{{…}}}”, this will cause the expression to be output unescaped.

3. Context

One of the concept of Handlebar JS is context where the properties you include in curly braces are looked up.

HTML:

<script id=”name-template” type=”text/x-handlebars-template”>

{{#each user}} <p>{{firstName}} {{lastName}}</p>

{{/each}}

</script>

<div class=”name-placeholder”></div>

JS:

$(function () {

var theTemplateScript = $(“#name-template”).html();

var theTemplate = Handlebars.compile(theTemplateScript);

var context = { user: [ { firstName: ‘Alex’, lastName: ‘Cutts’ }, { firstName: ‘Chris’, lastName: ‘Hale’ }, { firstName: ‘Christopher’, lastName: ‘Harris’ }, { firstName: ‘Rosie’, lastName: ‘Lane’ }, { firstName: ‘Ross’, lastName: ‘Lloyd’ } ] };

var theCompiledHtml = theTemplate(context);

$(‘.name-placeholder’).html(theCompiledHtml);

});

OUTPUT:

Alex Cutts
Chris Hale
Christopher Harris
Rosie Lane
Ross Lloyd

4. Blocks

If you want to focus your work on a particular expression within a template, then you can use blocks on Handlebar JS. It is represented with the pound (#) symbol that is followed by an expression and ends with a closing mustache, {{/expression}}.

HTML:

<script id=”name-template” type=”text/x-handlebars-template”>

<ul> {{#users}} <li>{{name}} – {{../company}}</li> {{/users}} </ul>

</script>

<div class=”name-placeholder”></div>

JS:

$(function () {

var theTemplateScript = $(“#name-template”).html();

var theTemplate = Handlebars.compile(theTemplateScript);

var data = { users: [ {name: “Alex Cutts”}, {name: “Chris Hale”}, {name: “Christopher Harris”} ], company: “Google” };

var theCompiledHtml = theTemplate(data);

$(‘.name-placeholder’).html(theCompiledHtml);

});

OUTPUT:

Alex Cutts – Google
Chris Hale – Google
Christopher Harris – Google

5. Helpers

With Handlebar JS helpers, you can call JavaScript from your templates. This can help you to reuse code also. You can just use it as an expression like {{helpername}} or as a parameters like {{helpername 123}}.

HTML:

<script id=”name-template” type=”text/x-handlebars-template”>

<p> “{{title}}” published at {{formatDate date}} by {{author}} </p>

</script> <div class=”name-placeholder”>

</div>

JS:

Handlebars.registerHelper(“formatDate”, function(date){ return date.getDay() + “/” + date.getMonth() + “/” + date.getFullYear(); });

$(function () {

var source = $(‘#name-template’).html();

var template = Handlebars.compile(source);

var post = {author: “John Doe”, title: “John’s Life”, entry: “It is the power of the mind to be unconquerable.”, date: new Date(Date.now())};

var post_html = template(post);

$(‘.name-placeholder’).html(post_html); });

OUTPUT:

“John’s Life” published at 1/7/2016 by John Doe

For further reading, click here to see full of great documentation and examples.

Jacob Frazier

Based on United States, Jacob Frazier is a skilled JavaScript developer with over 8 years of experience. He is passionate about change and trying new things, both professionally and personally. He loves startups and is extremely proactive.

Recent Posts

What Skills Do You Need to Become a Full-Stack Developer? A Complete Roadmap

Introduction There is an increasing need for full-stack developers because companies want people who can…

16 hours ago

The Enduring Influence Of Classic Russian Literature On Modern Storytelling

Classic Russian literature holds a quiet power that still shapes stories today. Its voice feels…

1 week ago

How Small Brands Can Make Physical Touchpoints Feel More Connected

Digital channels often get most of the attention in modern branding. A business can launch…

1 week ago

Kraftshala vs IIDE: The Real Numbers on Placements, Fees & Programs (2026)

If you have been researching digital marketing programs in India, Kraftshala and IIDE both keep…

3 weeks ago

Email Marketing That Drives Results: Strategies, Automation, and the Power of Email APIs

Email marketing remains one of the highest-performing digital marketing channels because it gives businesses direct…

3 weeks ago

Benefits of Manual Therapy for Faster Recovery from Muscle and Joint Pain

Pain in muscles and joints can be a problem in everyday life, whether it involves…

4 weeks ago