(A Comprehensive Handlebars.js Tutorial)

This is a complete tutorial, and indeed a reference, on Handlebars.js templating and, principally, JavaScript templating. Handlebars.js is a client-side (though it can be used on the server, too) templating engine for JavaScript. It is a JavaScript library that you include in your page just as you include any other JavaScript file. And with it, you can add templates to your HTML page that will be parsed and interpolated (values of properties inserted in place) with the values from the data you passed to the Handlebars.js function.





Can a Single JavaScript Course Make You Richer? This Single JavaScript Course Can Get You a Bigger Salary

(4 courses in 1—available as a single course for the first time) Becoming a JavaScript Expert Learn almost the entire JavaScript language, advanced JavaScript programming, software engineering for web programmers, and more 21 comprehensive major subjects and over 200 of the most important concepts covered (plus a bonus advanced course) Course covers from beginning to advanced to beyond advanced—including tooling, problem-solving, OOP, composition, software design patterns, software engineering foundation, architecting web applications, and much more Over 40 exercises and more than three dozen projects and applications

(Watching and/or reading JavaScript [JS] tutorials alone won't help you advance your programming career; you need to build real JS projects and applications as you learn. These exercises, projects, and applications are the most important part of your JS training. They will advance your JS confidence and skills and your overall programming and software engineering skills.) Every concept covered in depth and with clarity (if you don't understand something, we will update the course accordingly to add more clarity) Save yourself hundreds of hours and over $5,000 Plus: It comes with a HUGE BONUS, an entire advanced computer science JavaScript course: Discrete Math Concepts in JavaScript Become a JavaScript Pro and

significantly increase your income Learn More and Buy the Course By JavascriptIsSexy: Support the website while you simultaneously save yourself thousands of dollars



Written in JavaScript, Handlebars.js is a compiler that takes any HTML and Handlebars expression and compiles them to a JavaScript function. This derived JavaScript function then takes one parameter, an object—your data—and it returns a string with the HTML and the object properties’ values inserted into the HTML. So, you end up with a string that has the values from the object properties inserted in the relevant places, and you insert that string as HTML on the page.

Do I Have To Use a JavaScript Templating Engine? If so, Why?



Yes. If you develop or plan to develop JavaScript applications, you should use a JavaScript client-side templating engine to keep your JavaScript and HTML sufficiently decoupled; that is, keep your HTML separate from your JavaScript, which allows you to manage your HTML and JS files reliably and easily.

Sure, you can use JSDom, or you can fire up server-side templating and send your HTML files via HTTP. But I recommend client-side templating because it typically executes faster than server-side templating and it provides the easiest way to create and maintain your templates.

In addition, just about all the JavaScript front-end frameworks use a JavaScript templating engine, so you will eventually use JavaScript templating because you will likely use a JavaScript front-end or backend framework.

When to Use a JavaScript Templating Engine and Why to Use Handlebars.js?

The answers to both of these questions follow. Indeed, there exist some specific use cases for JavaScript templating engines.

When To Use a JavaScript Templating Engine?

You should use a JavaScript templating engine like Handlebars.js when:

You use a JavaScript front-end framework like Backone.js, Ember.js, and the like; most front-end JavaScript frameworks rely on templating engines

The application’s view (the HTML page or portions of the page) will be updated frequently, especially as a result of changes to the data either from the server via a REST API or from data on the client

You have multiple tech stacks that depend on your data from the server and you want all the tech stacks to process the same data

Your application has much interactivity and it is very responsive

You are developing a single-page web application with multiple views

You want to easily manage your HTML content; you don’t want your JavaScript code to contain important HTML markup. Here is an example of JS code with HTML markup (it makes it difficult to manage your HTML markup): shoesData.forEach (function (eachShoe) { //Note the intermingling of HTML and JavaScript; it is tedious to follow: theHTMLListOfShoes += ' ' + '' + eachShoe.name + ' -- Price: ' + eachShoe.price + ' '; }); return theHTMLListOfShoes; }



Why Use Handlebars.js (out of the eight or more templating engines)?

Unsurprisingly, there are many JavaScript client-side templating engines, but we will focus on only Handlebars.js in this tutorial, since it is the best of the lot. Some of the other worthy templating engines are Underscore.js’ Template, Mustache.js, EJS, and Dust.js.

Handlebars.js is an extension of the Mustache JavaScript templating language; it supersedes Mustache.js.

The reasons you should use Handlerbars.js follow:

Handlebars is one of the most advanced (pre-compiling and the like), feature-rich, and popular of all the JavaScript templating engines, and it has the most active community.

Handlebars is a logic-less templating engine, which means there is little to no logic in your templates that are on the HTML page. The most important use of Handlebars, and any templating engine, is to keep your HTML pages simple and clean and decoupled from the logic-based JavaScript files, and Handlebars serves this purpose well. Indeed, Dust.js is also a logic-less templating engine and a worthy alternative to Handlebars.js.

Moreover, the cutting-edge JavaScript frameworks Meteor.js and Derby.js, which we will cover in upcoming posts, are expected to become mainstream in the coming months, and both use Handlebars.js. To be clear: Meteor.js uses Handlebars.js and Derby.js “template syntax is largely based on Handlebars” template syntax. And Ember.js uses Handlebars, too. While Backbone.js is packaged with Underscore.js templating engine, it is super easy to use Handlebars.js with Backbone.js. Therefore, the experience and knowledge you will have gained from learning Handlebars.js now will be well worth it, if you use, or plan to use, any of the noted JS frameworks.

In short, learning Handlebars.js now is an investment and a wise choice: you will program more effectively now and you will adapt easily to the JS frameworks tomorrow and in the coming weeks and months.

Handlebars.js Overview

Now that we have seen how to use Handlebars in a simple application, let’s study Handlebars in detail.

How Handlebars.js Works?

As noted in the introduction: Handlebars.js is a compiler built with JavaScript that takes any HTML and Handlebars expression and compiles them to a JavaScript function. This derived JavaScript function then takes one parameter, an object—your data—and it returns an HTML string with the object properties’ values inserted (interpolated) into the HTML. So, you end up with a string (HTML) that has the values from the object properties inserted in the relevant places, and you insert the string on a page.

This sounds way more complex that it is, so let’s take a closer look.

The 3 Main Parts of Handlebars Templating

To use Handlebars, first you link to the Handlebars.js file in the head block of your HTML page, just like you do for jQuery or any .js files.. Then there are 3 main pieces of code you use for Handlebars templating:

<

ol>

Handlebars.js Expressions

A simple Handlebars expression is written like this (where “content” can be a variable or a helper function with—or without—parameters: {{ content }} Or like this, in the case of Handlebars block expressions (which we will discuss in detail later): {{#each}} HTML content and other Handlebars expresion go here. {{/each}} Below is a Handlebars expression with HTML. The customerName variable is the property that will be interpolated (its values will be inserted in place) by the Handlebars.compile function: Name: {{ customerName }} The output will be the following (if the customerName variable has the value “Richard”): Richard Since you have to pass the Handlebars expression (with any containing HTML) to the Handlebars.compile function, a script tag is used to enclose each Handlebars template when they are on the HTML page. Indeed, the script tag is not necessary when a template is in its own HTML file, but it is necessary when the Handlebars template is on the page along with other Handlebars template and other HTML content. — Script Tag

Handlebars templates are embedded in script tags (where the script tag’s type property is set to “text/x-handlebars-template”). The script tag is similar to the script tag you normally use to embed JavaScript in the HTML page, except the type attribute is different. You retrieve the HTML content from the script tag and pass it to the Handlebars compiler. Here is an example of the Handlebars script tag:

Data (or Context)

The second piece of code in Handlebars templating is the data you want to display on the page. You pass your data as an object (a regular JavaScript object) to the Handlebars function. The data object is called the context. And this object can be comprised of arrays, strings, numbers, other objects, or a combination of all of these. If the data object has an array of objects, you can use Handlebars each helper (more on helpers later) function to iterate the array, and the current context is set to each item in the array. Here are examples of setting up the data object and how to iterate it in a Handlebars template. — Data object with array of objects //The customers object has an array of objects that we will pass to Handlebars: var theData = {customers:[{firstName:”Michael”, lastName:”Alexander”, age:20}, {firstName:”John”, lastName:”Allen”, age:29}]}; You can use the each helper to iterate the customer’s object like this: Or, since we are passing the customer’s object as an array of objects, we can use a block helper (more on block helpers later) statement like this and reference the customers directly: — Data object with Strings // In this example, the data object contains properties with strings: var theData = {headerTitle:"Shop Page", weekDay:”Wednesday”};

The Handlebars Compile Function

The last piece of code we need for Handlebars templating is actually a two-step execution:

1. Compile the template with the Handlebars.compile function.

2. Then use that compiled function to invoke the data object passed to it (it takes a data object as its sole parameter). And this will return an HTML string with the interpolated object values inserted into the HTML. In short:

The Handlebars.compile function takes the template as a parameter and it returns a JavaScript function. We then use this compiled function to execute the data object and return a string with HTML and the interpolated object values. Then we can insert the string into the HTML page.

Here are the 3 pieces together:

1. On the HTML age: Setup the templates by using Handlebars expressions, and add the templates to a script tag (if using script tags: templates in individual HTML files don’t need script tags):

2. In the JavaScript file: Initialize the data object

var theData = {headerTitle:"Shop Page", weekDay:”Wednesday”}; // Retrieve the HTML from the script tag we setup in step 1 // We use the id (header) of the script tag to target it on the page var theTemplateScript = $("#header").html();

3. Also in the JavaScript file: Then we use the Handlebars compile function to compile the templates.

Compile the template retrieved from the script tag:

// The Handlebars.compile function returns a function to theTemplate variable var theTemplate = Handlebars.compile (theTemplateScript);

Use the theTemplate () function returned by the compile function to generate the final string with interpolated object values. We pass the object data as a parameter. Then attach the resulting string with HTML to the page:

$(document.body).append (theTemplate (theData));

This will return our HTML with the values from the object inserted in place, and the result will look like this:

__________

Shop Page

Today is Wednesday

Compare a Non-Handlebars Project With a Handlebars.js Project

To get a high-level overview of what development with Handlebars entails when compared with non-JavaScript templating, let’s build a quick, tiny JavaScript project.

Before we use Handlebars, let’s make use of jQuery and JavaScript without Handlebars, to get a sense of what we are building and how Handlebars will make a difference.

Without Handlebars, this is what a typical JavaScript/jQuery project will look like when you have content to add to the page with some data. We are simply displaying a list of shoes and prices .

A Little Non-Handlebars Project

Download Handlebars.js and jQuery:

Download the latest version of Handlebars from Github (we are not using it yet, though, but still include it on the page). Get the full version, not the “runtime only” version (more on the runtime version later): https://github.com/wycats/handlebars.js/downloads Also, download the latest version of jQuery here (we will use it throughout this tutorial): http://code.jquery.com/ Create a new directory on your computer named “Handlebars_tuts” and place the jQuery and Handlebars.js files in it. Or, you can open Terminal (on MAC) and change directory to the “Handlebars_tuts” directory. Then type the following commands to download both JS files directly to the directory with the curl command: curl http://code.jquery.com/jquery-1.9.1.min.js > jquery-1.9.1.min.js curl https://github.com/downloads/wycats/handlebars.js/handlebars-1.0.rc.1.min.js > Handlebars.js Make an index.html file and add the following The List of Shoes: Create a main.js file and add the following:

Note this JS file has both HTML and JavaScript mixed together in an unhealthy soup $(function () { var shoesData = [{name:"Nike", price:199.00 }, {name:"Loafers", price:59.00 }, {name:"Wing Tip", price:259.00 }]; function updateAllShoes(shoes) { var theHTMLListOfShoes = ""; shoesData.forEach (function (eachShoe) { // Note the coupling and mixing of HTML and JavaScript; it is tedious to follow theHTMLListOfShoes += ' ' + '' + eachShoe.name + ' -- Price: ' + eachShoe.price + ' '; }); return theHTMLListOfShoes; } $(".shoesNav").append (updateAllShoes(shoesData)); }); ￼

If you open the index.html file in your browser, you should see a simple list with 3 items. This is how we normally develop on the front end without a JavaScript template engine.

A Little Handlebars Project

Now, lets refactor the code above and use Handlebars.js templating instead of relying on HTML and JavaScript coupled together “unhealthily.”

Changes to index.html: First, just below the link to the jquery.js file (e.g., ), add the link to the handlebars js file. Whatever the name of the handlebars file is, add it, like this:

Second, add this code just below the closing ul tag Changes to main.js:

And here is the refactored JS code that makes use of Handlebars.

Remove all the JS code and replace with the code below

— Note that we have gotten rid of the entire updateAllShoes functions

— And also note there is no HTML in the JS file anymore, all the HTML now live in the HTML file. $(function () { var shoesData = [{name:"Nike", price:199.00 }, {name:"Loafers", price:59.00 }, {name:"Wing Tip", price:259.00 }]; //Get the HTML from the template in the script tag var theTemplateScript = $("#shoe-template").html(); //Compile the template var theTemplate = Handlebars.compile (theTemplateScript); $(".shoesNav").append (theTemplate(shoesData)); //We pass the shoesData object to the compiled handleBars function // The function will insert all the values from the objects in their respective places in the HTML and returned HTML as a string. Then we use jQuery to append the resulting HTML string into the page }); When you refresh the index.html page in your browser should see the same output we had in the previous non-Handlebars example above. The preceding illustrate the very basic use of Handlebars.js. As you have seen, using Handlebars allowed us to separate the HTML from the JavaScript. This is even more important as our application gets more complex; the easier it will be to develop separate template files and manage them effectively. Whereas, the non-Handlebars example would be a mess to manage as our application gets larger.

That in essence is how using Handlebars.js allows us to keep our HTML files decoupled from our JavaScript files.

The Main Difference Between the Two Projects

This is the main difference between the non-Handlebars.js project and the Handlebars.js project: The non-Handlebars.js project has important HTML markup inside the JavaScript code, which makes it difficult to manage (create and update) the HTML:

// You can see the HTML and JS intermingled function updateAllShoes(shoes) { var theHTMLListOfShoes = ""; shoesData.forEach (function (eachShoe) { theHTMLListOfShoes += ' ' + '' + eachShoe.name + ' -- Price: ' + eachShoe.price + ' '; }); return theHTMLListOfShoes; } $(".shoesNav").append (updateAllShoes(shoesData));

While the Handlebars.js project’s JavaScript code does not contain the HTML markup (the HTML markup is on the HTML page; only JS is in the JS code):

var theTemplateScript = $("#shoe-template").html(); var theTemplate = Handlebars.compile (theTemplateScript); $(".shoesNav").append (theTemplate(shoesData));