Using Handlebar Templates in Apache Cordova

By Rob Gravelle

Using Handlebar Templates in Apache Cordova

The Apache Cordova framework uses JavaScript APIs that allow you to develop smartphone apps using familiar web languages such as HTML, CSS, and JavaScript. In addition to being consistent across multiple device platforms, the Cordova JavaScript APIs also make it easy to employ popular UI frameworks such as jQuery Mobile, Dojo Mobile, Sencha Touch, and more specialized libraries such as Handlebars.js. The latter is a JavaScript library that helps you to programmatically insert HTML fragments into your pages. HTML templates have been around for a long time and are a great way to reuse page elements without a lot of (or even any) coding. In today's article, we'll streamline the app code produced in the Using Views in Apache Cordova article by decoupling HTML markup from the application logic.

What do Moustaches Have to Do with HTML Templates???

The name "Handlebars" doesn't refer to those on a bicycle. These handlebars are named after the moustache! Or, more specifically, the Moustache template system. Introduced in late 2009, the template engine was implemented with Ruby, running YAML template texts. Now there are Mustache implementations for several different languages including Ruby, JavaScript, Python, PHP, Perl, Objective-C, Java, .NET, Android, C++, and others. Mustache is known for its "logic-less" template syntax because that doesn't rely on procedural statements like if, else, for, etc. Rather, Mustache templates are entirely defined with tags.

The library got its name because of its heavy use of curly braces that resemble a mustache!

Hello {{name}}

The library that we will be using here today is the Handlebars library, which is an extension of the original Moustache JavaScript implementation. Hence, it's a superset of Moustache that includes all of the original functionality and more.

Defining your Templates

Before we begin, you should probably take a look at my Using Views in Apache Cordova article for details on how to make the search work.

The official Apache Cordova Tutorial also has the source files that you'll need to get started.

Start by creating an HTML template to render the Home View. Add the following script tag immediately after the opening <BODY> tag:

<script id="home-tpl" type="text/template">
    <header class="bar bar-nav">
        <h1 class="title">Directory</h1>
    <div class="bar bar-standard bar-header-secondary">
        <input class='search-key' type="search"/>
    <div class="content"></div>

As you can see, the template uses a script tag, but with a special type.

This HTML template renders a list of employees. Add it immediately after the previous one:

<script id="employee-list-tpl" type="text/template">
    <ul class="table-view">
        {{#each this}}
        <li class="table-view-cell media">
          <a href="#employees/{{ id }}">
              <img class="media-object pull-left" src="assets/pics/{{pic}}">
              <div class="media-body">
                  {{firstName}} {{lastName}}

Of course none of the above templates will show up correctly without the handlebars library. You can download it from official site or from GutHub. All you need to make it work is a reference to the handlebars.js script. Like any JavaScript file, you can either place it in the document <HEAD> section, or at the bottom of the body:

<script src="lib/handlebars.js"></script>

Compiling Templates

Before templates can be inserted into the document, they must be compiled. The static Handlebars.compile() method accepts a string containing the template markup. In the immediate function in app.js, right before the service variable declaration, declare two variables to store the compiled version of the templates defined above:

var homeTpl         = Handlebars.compile($("#home-tpl").html());
var employeeListTpl = Handlebars.compile($("#employee-list-tpl").html());

Now we need to modify renderHomeView() to use the homeTpl template instead of the inline HTML:

function renderHomeView() {
    $('.search-key').on('keyup', findByName);

Last but not least, update findByName() to use the employeeListTpl template instead of the inline HTML:

function findByName() {
    service.findByName($('.search-key').val()).done(function (employees) {

Styling your Application UI

Your mobile apps should look like mobile apps and not like a regular web page - a distinct possibility when your UI is made up of HTML fragments! Not only do mobile apps tend to have a distinctive look and feel, but each platform has its own slightly different look and feel. Even so, mobile apps have evolved to look and behave a certain way, largely based on the limited real estate of the screen, and touch capabilities. You'd be foolhardy to try to emulate the appearance of each device vendor. It's far better to employ one of the many excellent CSS libraries for that purpose.

The one that we'll be using here is called Rachet. We don't even need the whole library; just reference the ratchet.css and styles.css files in the head of index.html:

<link href="assets/ratchet/css/ratchet.css" rel="stylesheet">
<link href="assets/css/styles.css" rel="stylesheet">


Apache Cordova's to be seamlessly integrated with other libraries such as Handlebars.js and Rachet is one of its best features. In theory, the less code you have to write yourself, the shorter the development process.

Rob Gravelle

Rob Gravelle resides in Ottawa, Canada, and is the founder of Rob has built systems for Intelligence-related organizations such as Canada Border Services, CSIS as well as for numerous commercial businesses.

In his spare time, Rob has become an accomplished guitar player, and has released several CDs. His band, Ivory Knight, was rated as one of Canada's top hard rock and metal groups by Brave Words magazine (issue #92) and reached the #1 spot in the National Heavy Metal charts on Reverb Nation.

Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
Thanks for your registration, follow us on our social networks to keep up-to-date