5 min read

(For more resources related to this topic, see here.)

Preparing the project

To get started, create a file named index.htmland 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.

Summary

Thus we have learned how to create template in this article.

Resources for Article:


Further resources on this subject:


LEAVE A REPLY

Please enter your comment!
Please enter your name here