Basic Javascript Templates with Handlebars

I have recently worked on a project using Javascript with Handlebars as a templating engine. I do not claim to be a Handlebar, or Javascript, expert, I am just making note of what I have learned for future reference and maybe something I write here will benefit someone else who trying to get started with Handlebars.

I have made a simple little example project with some sports themed data. My data is a collection of sports leagues. Each league has a Name, an acronym, the year it was founded, and can have a collection of teams. Each team has a city, a name, and a division. The structure in Json form is this:

var sportData = {
    league: [
        { name: "National Hockey League", acronym: "NHL", founded: 1917, },
	{ name: "Major League Baseball", acronym: "MLB", founded: 1869, },
        { name: "National Basketball Association", acronym: "NBA", founded: 1946, },
        { name: "National Football League", acronym: "NFL", founded: 1922, },
        { name: "Major League Soccer", acronym: "MLS", founded: 1993, },

In theory this is something that is returned from an API, but for the purpose of this small example, in code will work. So the question is, how can I easily display this data? The answer that I am covering in this blog is……Handlebars. Shocker, right?

So here is my simple Handlebars template to plop that data into the web page for me.

<script id="sports-template" type="text/x-handlebars-template">
    <div id="sport-list">
            {{#each league}}
                <label>{{{name}}} ({{acronym}}) [Founded {{{founded}}}]</label>


So let’s break this down. This really is just HTML with some handlebars bits injected. So I have a container div I call sport-list. This literally is just a wrapper div that I choose to put. It is not used for anything at the moment. Next I have a <ul> to start my list. Just below that, there is the first bit of handlebars notation, which is {{#each league}}. This is essentially a foreach that is seen in many other languages. So {{#each league}} will look for an object called league within the current data context. Then, for each object within the league object, handlebars will repeat the chunk of code until the matching {{/each}}. Inside of the each, there is an <li> just to make each entry its own list item, then a boat load of curly braces. The first handlebars bit is {{{name}}}, which tells handlebars to put whatever is in the object called “name” there. Then {{{acronym}}} tells handlebars to put whatever is in the object call “acronym” in that place. I am sure that you can now guess what {{{founded}}} does. If any of that data is missing, handlebars essentially leaves it blank.  The last bit of important information is the id on the script tag. That will be what is given to handlebars to let it know what template to use.

Before you can use a handlebars template on a webpage, it needs to compiled. To do that, we have to call “Handlebars.compile()” and pass in the id of the script that you want compiled, in my case that is “sports-template.” I have chosen to put the actual Handlebars.compile call inside of an object called “handlebarsSample” that will also be used to hold as much of the handlebars related javascript as possible. “handlebarsSample” looks like this:

var handlebarsSample = function () {
    function compileTemplate(scriptId) {
        if (scriptId[0] != "#") {
            scriptId = "#" + scriptId;

        return Handlebars.compile($(scriptId).html());

    function registerPartials() {
        //No partials right now

    function registerHelpers() {
        //No Helpers right now

    return {
        compileTemplate: compileTemplate,
        registerPartials: registerPartials,
        registerHelpers: registerHelpers,

To explain this, I will start at the top. The first thing I do is define an object called “handlebarSample,” which is just a function used to house other objects. Currently, those three objects are registerPartials, registerHelpers, and compileTemplate. The two registers are not currently being used because my sample is too simple to need them yet, so I am not going to explain them. They are just placeholders at the moment. compileTemplate, however, is used. That is where I am actually calling the Handlerbars.compile function. This allows me to do some validation or error checking of the script Id that I want to compile. My case I am just making sure that I have the needed “#” that jquery uses to find Ids in the DOM. If the first character is not a “#” put one, then pass that to the compile function, which is returned from this function to where ever the call to it was made.

So now I have data. I have made a template. I have compiled that template. But I have nothing showing up on my webpage yet.  That is because we have not yet plugged the data and template together, nor have we injected the result. The first step is to actually compile the template.

var sampleTemplate = handlebarsSample.compileTemplate("sports-template");

Then I want to take that result, plug the data into, and put it somewhere on the page.


Lets work inside-out for this. The sampleTemplate(sportData) is where I plug my data into the handlebars template. Then I use a basic jquery selector to grab the appropriate div, then I just append the results that div which gives the output of:

National Hockey League (NHL) [Founded 1917]
Major League Baseball (MLB) [Founded 1869]
National Basketball Association (NBA) [Founded 1946]
National Football League (NFL) [Founded 1922]
Major League Soccer (MLS) [Founded 1993]

That is the very basics using handlebars. There is a more I plan to cover, including partials and helpers in future blogs, hopefully soon (no promises).

For the full source look at these two files.

One thought on “Basic Javascript Templates with Handlebars

  1. Pingback: JavaScript Handlebars Templates with Partials | //InterKnowlogy/ Blogs

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>