Reme Le Hane

Introduction to Handlebars

If your site’s data regularly changes, then you might want to take a look at Handlebars. Handlebars is a template processor that dynamically generates your HTML page, saving you time from performing manual updates. In this tutorial, I’ll introduce you to Handlebars, and teach you how to create a basic template for your site.

—-

Site Template

There are two primary reasons why you’d want to make a template for your site. First of all, building a template encourages you to separate the logic-based code from the actual view, helping you adhere to a View/Controller pattern. Secondly, templates keep your code clean and maintainable, which, in turn, makes the process of updating your site a breeze. You don’t create a site with Handlebars. Instead, you create guidelines and structures that dictate how the site should look without focusing on a page’s data. Let’s cover some of the basics.
—-

The Basics

Handlebars generates your HTML by taking a JSON structure and running it through a template. These templates are written mostly in regular HTML, and are peppered with placeholders that allow you to inject data, as needed. For example, the following template greets the user when they log in:

Welcome back, {{name}}

The {{name}} attribute is where the user’s name will be injected into the page. This placeholder corresponds with a property in the data’s JSON structure. This is the most basic example possible, but you will soon see that everything else basically boils down to this simple concept. Let’s move on to handling arrays.

Arrays

Handlebars comes with some built-in helpers to assist you in working with more complex data. One of these helpers is the each helper. This helper iterates through an array and allows you to create dynamic HTML, per array element. For example, the following template displays an array’s data that contains a list of the local concerts playing in my area:

Local Concerts

{{#each Concerts}}
{{this}}

{{/each}}

As you can see, this code is much cleaner than conventional code, such as using a loop in PHP or JavaScript to append HTML to a variable. Handlebars is not intrusive, and this is what makes Handlebars so accessible. You may also notice that we use the attribute name, this, to retrieve the current array element in the each loop.

This example is good for an array of simple values, but how do you handle more complex data? Well, you essentially do the same thing. For example, we’re going to write a template for the following data: [ { Name : “Band”, Date : “Aug 14th, 2012”, Albums : [ { Name : “Generic Name” }, { Name : “Something Else!!” } ] }, { Name : “Other Guys”, Date : “Aug 22nd, 2012” Albums : [ { Name : “Album One” } ] } ]

We can easily display this information using the following template:

Band Name
Date
Album Name

{{#each Bands}}
{{Name}}
{{Date}}
{{Albums.0.Name}}

{{/each}}

You can store your template in a

For convenience, you can store your template in a

If your site’s data regularly changes, then you might want to take a look at Handlebars.

This is the complete code for compiling and generating HTML code from a template. You can technically pass the JSON data from the API directly into Handlebars, but you run into cross origin issues. Instead of performing some sort of hack or using PHP to “echo” the data into a JavaScript variable, I decided to put all of that into a separate file: Recipe.php. So before we start building the template, let’s go take a look at that PHP file.

Getting The Data

The Yummly API is pretty simple. There is no elaborate authentication system; you just have to sign up, get some credentials, and insert them into the URL. You can directly echo the data if you want to, but I want a bit more detailed info on each recipe. Therefore, I will process the data from the first API call and make a second request for every recipe. Here is the complete PHP script:

By building your site with a Handlebars template, you can produce a full site’s worth of code in only a few lines. Here is the entire template:

Let’s run through this code. The first seven lines are just the logo at the top of the page. Then for each recipe, we create a recipe ‘card’ with a picture, name, and ingredients.

The Yummly API returns a list of flavor data (i.e. how sweet, sour, spicy, etc..) for each item. I wrote a function helper, called getFlavor that takes this info and returns the most dominant flavor in the dish. In order for this template to work, we need to load in the getFlavor helper into Handlebars before parsing the template. So at the beginning of the second script section, add the following code before the Ajax code: Handlebars.registerHelper(“getFlavor”, function(FlavorsArr){ var H = 0; var Name = ”; for(var F in FlavorsArr) { if(FlavorsArr[F] > H) { H = FlavorsArr[F]; Name = F; } } return “This Dish has a ” + Name + ” Flavor”; });

Now, whenever Handlebars sees getFlavor, it calls the associated function and retrieves the flavor information.

At this point, you are free to play around and design the template however you wish, but you will most likely see that this process is slow. This is primarily due to the three API calls before Handlebars loads the page. Obviously, this is not ideal, but precompiling your template can help.
—-

Precompiling

You have two different options, when it comes to Handlebars. The first is to just precompile the actual template. This reduces the loading time, and you won’t have to include the Handlebars compiler with your page.

This also results in a smaller file size, but this doesn’t really help in our scenario.

Our problem is the communication between the browser and the API. If you did want to precompile your template, you can download the Node.js package through npm with the following command: npm install handlebars -g

You may need to do this as root (i.e. add ‘sudo’ before the command). Once installed, you can create a file for your template and compile it like so: handlebars demo.handlebars -f demo.js

You should give your template file a .handlebars extension. This is not mandatory, but if you name it something like demo.html, then the template’s name will be “demo.html” as apposed to just “demo”. After naming your template, simply include the output file along with the run-time version of Handlebars (you can use the regular version, but it’s larger) and type the following: var template = Handlebars.templates[‘demo’]; var html = template({ Your Json Data Here });

The unless statement is…essentially an inverted if statement.

But, as I mentioned before, this doesn’t really help us in this scenario. What then can we do? Well, we can precompile and output the entire file. This makes it so that we can run the template with data and save the final HTML output – caching, in other words. This drastically speeds up the load time of your application. Unfortunately, client-side JavaScript doesn’t have file IO capabilities. So, the easiest way to accomplish this is to just output the HTML to a text box and manually save it. Be aware of an API’s guidelines on caching. Most APIs have a maximum amount of time that data can be cached for; make sure to find that information before saving static pages.
—-

Conclusion

This has been a quick introduction to Handlebars. Moving forward, you can look into “Partials” – small templates that can be used like functions. As always, feel free to leave a comment or question in the comment section below.


http://goo.gl/LhR8k Reme Le Hane


To Tumblr, Love PixelUnion