• Handlebars
  • Tutorial

How it works

Handlebars is a JavaScript templating engine. It allows us to inject JavaScript property values directly into our HTML. Handlebars is a compiler. This means that it takes some input, it compiles or transforms that input, and gives us a result.

In this case, our input will be HTML strings, with Handlebars expressions like color. The result will be a function that takes one parameter, called a context. The context is just a JavaScript object. We can assign that function to a variable, and then call that function with a JavaScript object. And what we'll get back is a string that has our original HTML interpolated with the values of the object.

Let's take a look at an example. First, I'm going to download the minified JavaScript file for Handlebars. And then I'm going to download jQuery so that I have both of these files in my local project directory. Then I'll create an index.html file, and an app.js file. Next, I'll paste in some HTML, and I'll include the jQuery Handlebars and app.js scripts, and then just put in an empty body.

Over in our JavaScript file, I'll use jQuery to wait for the download to be ready. And then, let's create a source string. Then I'll take this source string, and I'll use Handlebars to compile it and assign it to the template variable.

Finally, I'll create a context. The context has one property called color, which is blue. And then I'll get the HTML by calling the template method with the context as a parameter. And then I'll take this resulting HTML and append it to the body using jQuery. Over in the browser, I can see that blue is rendered onto the page. And we can see that the HTML that was produced is our original Handlebars expression interpolated with the blue value of our context object.

But it'd be sort of annoying if we always had to assign are templates to a variable as a string. So, there's a better way. What we can do is, directly in our HTML page, we can include a script tag. We'll give it an ID so we can reference it later. And a type of text x-handlebars-template. And within the script tag, we can put our Handlebars template.

Now, over in our JavaScript file, we'll replace the string that we assigned to source. And instead, we'll use jQuery. We'll grab the template by ID and get the HTML using the HTML method. Over in the browser, we can see that it still works.