Book Image

Instant Handlebars.js

By : Gabriel Manricks
Book Image

Instant Handlebars.js

By: Gabriel Manricks

Overview of this book

Handlebars is one of the leading JavaScript templating engines and is quickly gaining widespread adoption by developers, as well as with frameworks like Ember.js and Meteor. "Instant Handlebars.js" is a complete guide to the Handlebars library filled with internal concepts and practical examples that will help illustrate what's going on and take you from a complete beginner to a Handlebars expert. "Instant Handlebars.js" begins with the very basics, requiring no previous knowledge about templating engines. Throughout the course of this book, you get a thorough tour of all the features available in Handlebars.js and you will learn how to organize your websites for both development and production. In this book, we will cover how to create templates with both placeholders and helpers. We will then go into organizing your projects for rapid -development using Require.js and how to optimize and compile your projects for production. To finish off, you will learn how to annotate your code and leave debug points so that you can easily maintain and troubleshoot your code in the future. Handlebars is a small library;, it is meant to fill a specific need and it does this well. "Instant Handlebars.js" takes a very methodical approach to cover every aspect of this amazing library with practical examples provided every step of the way.
Table of Contents (7 chapters)

Quick start – creating your first template


Let's start from the beginning. The purpose of using a templating engine such as Handlebars is to generate some kind of viewable content (usually HTML pages), dynamically. This encompasses a really broad range of uses, from e-mail newsletters, web apps, and really any other kind of output format around.

In this quick start, we will take a brief look at the process of creating a template with both placeholders and helper tags, and then how to run and output the contents to the page.

Preparing the project

To get started, create a file named index.html and add the following boilerplate code:

<!DOCTYPE HTML>
<html>
  <head>
    <title>Handlebars Quickstart</title>
    <script src="handlebars.js"></script>
  </head>
  <body>
    <script>
      var src = "<h1>Hello {{name}}</h1>";
      var template = Handlebars.compile(src);

      var output = template({name: "Tom"});
      document.body.innerHTML += output;
    </script>
  </body>
</html>

This is a pretty good example to start with, as it demonstrates the minimum amount of code you will need to write to get a template on screen. We will start it by writing the template itself, just a pair of header tags with a greeting message inside. If you remember from the introduction, a Handlebars tag is a reference for some external data wrapped between two pairs of curly braces, and it signifies a dynamic point in the page where Handlebars will insert some information. Here we just want a property called "name" to be inserted at this point, which we will set in a moment. Once you have the template, the next step is where all the magic begins; Handlebars compile function will process through the template's source and generate a JavaScript function to output the result. What I mean by this is Handlebars will create a function that accepts some data and returns the final string with all the placeholders replaced.

An example of what I mean could be something like the following code for our quick template stated in the preceding paragraph:

var template = function (data) {
    return "<h1>Hello " + data.name + "</h1>";
}

And then every time the template gets called with data, the resulting string will be passed back. Now obviously it is a bit more complex than this, and Handlebars performs some escaping for you and other such checks, but the basic idea of what the compile function generates remains the same.

So with our template function created, we can call it by passing in some data (in this case the name Tom), and we take the output and append it to the body. After opening this page in a browser, you should see something like the following screenshot:

With the basics out of the way, let's take a look at helpers.

Block helpers

Helpers can be called in the same way as the data placeholder was called from the template. The difference between them is that a data placeholder will just take a static string or number and insert it into the template's output. Helpers on the other hand are functions, which first compute something, and then the results get placed into the output instead. You can think of helpers as a more dynamic form of placeholders.

Now there are two types of helpers in Handlebars: tag helpers, which work like regular functions; and block helpers, which have an added, nested template to manipulate.

Handlebars comes with a series of block helpers built-in, which allows you to perform basic logic in your templates. One of the most commonly used block helpers in Handlebars would have to be the each helper, which allows you to run a section of template per item in an array. Let's take a look at it in action.

It is going to be too messy to continue placing the templates into JavaScript strings like we did in the first example, so we will place it in its own script tag and pull it in. The reason we are using a script tag is because we don't want the template to show up on the page itself; by placing it in a script tag and setting the type to something the browser doesn't understand it will just be ignored. So right on top of the script tag block that we just wrote, add the following code:

<script id="quickstart" type="template/handlebars">
  <h1>Hello {{name}}</h1>
  <ul>
    {{#each messages}}
      <li><b>{{from}}</b>: {{text}}</li>
    {{/each}}
  </ul>
</script>

We give the script tag an id, so we can access it later, and then we give it an arbitrary type, so that the browser doesn't try to parse it as JavaScript. Inside it we start with the same template code as before, and then we add each block to cycle through a list of messages and print out each one in a list element.

The next step is to replace the script block underneath with the new code, which will get the template from here:

<script>
    var src = document.getElementById('quickstart').innerHTML;
    var template = Handlebars.compile(src);

  var output = template({
    name: "Tom",
    messages: [
      { from: "John", text: "Demo Message" },
      { from: "Bob", text: "Something Else" },
      { from: "John", text: "Second Post" }
    ]
  });
  document.body.innerHTML += output;
</script>

We start by pulling the template from the script block we added in the previous paragraph using standard JavaScript; next we compile it like before and run the template, this time with the added "messages" array. Running this in your browser will give you something like the following:

You may have picked up on this, but it's worth mentioning, that inside each block the context changes from the global data object passed into the template to the specific array element, because of this we are able to access its properties directly.

These first few steps have been simple, but subtly we have covered loading in templates from script tags, and the syntax for both standard placeholders as well as block helpers in your templates.