SHARE
Facebook X Pinterest WhatsApp

Using Handlebar Templates in Apache Cordova

Written By
thumbnail
Rob Gravelle
Rob Gravelle
Jan 13, 2015

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.

Advertisement

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>
    </header>
    <div class="bar bar-standard bar-header-secondary">
        <input class='search-key' type="search"/>
    </div>
    <div class="content"></div>
</script>

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}}
                  <p>{{title}}</p>
              </div>
          </a>
        </li>
        {{/each}}
    </ul>
</script>

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>
Advertisement

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() {
    $('body').html(homeTpl());
    $('.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) {
        $('.content').html(employeeListTpl(employees));
    });
}
Advertisement

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">
Advertisement

Conclusion

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.

Recommended for you...

The Revolutionary ES6 Rest and Spread Operators
Rob Gravelle
Aug 23, 2022
Ahead of Time (AOT) Compilation in Angular
Tariq Siddiqui
Aug 16, 2022
Converting a JavaScript Object to a String
Rob Gravelle
Aug 14, 2022
Understanding Primitive Type Coercion in JavaScript
Rob Gravelle
Jul 28, 2022
HTML Goodies Logo

The original home of HTML tutorials. HTMLGoodies is a website dedicated to publishing tutorials that cover every aspect of being a web developer. We cover programming and web development tutorials on languages and technologies such as HTML, JavaScript, and CSS. In addition, our articles cover web frameworks like Angular and React.JS, as well as popular Content Management Systems (CMS) that include WordPress, Drupal, and Joomla. Website development platforms like Shopify, Squarespace, and Wix are also featured. Topics related to solid web design and Internet Marketing also find a home on HTMLGoodies, as we discuss UX/UI Design, Search Engine Optimization (SEO), and web dev best practices.

Property of TechnologyAdvice. © 2025 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.