Quick start – creating your first template

Exclusive offer: get 50% off this eBook here
Instant Handlebars.js [Instant]

Instant Handlebars.js [Instant] — Save 50%

Learn how to create and implement HTML templates into your projects using the Handlebars library with this book and ebook

$12.99    $6.50
by Gabriel Manricks | November 2013 | Open Source Web Development

In this article by Gabriel Manricks, author of the book Instant Handlebars.js, we will learn how to create 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.

(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:


Instant Handlebars.js [Instant] Learn how to create and implement HTML templates into your projects using the Handlebars library with this book and ebook
Published: September 2013
eBook Price: $12.99
See more
Select your format and quantity:

About the Author :


Gabriel Manricks

Gabriel Manricks is a full stack software & web developer focusing on PHP and both frontend and server-side JavaScript frameworks.

Gabriel works as a staff writer for NetTuts+, where he enjoys learning as well as teaching others, and he also freelances in web consulting, development, and writing.

Books From Packt


Instant typeahead.js [Instant]
Instant typeahead.js [Instant]

Instant Zepto.js [Instant]
Instant Zepto.js [Instant]

Ext JS 4 First Look
Ext JS 4 First Look

Instant Node.js Starter [Instant]
Instant Node.js Starter [Instant]

Backbone.js Testing
Backbone.js Testing

Learning Ext JS 3.2
Learning Ext JS 3.2

 Instant Ember.js Application Development How-to [Instant]
Instant Ember.js Application Development How-to [Instant]

Instant AngularJS Starter [Instant]
Instant AngularJS Starter [Instant]


Your rating: None Average: 1.5 (4 votes)

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
N
B
Z
x
a
q
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software