Tuesday, March 19, 2024

Using Handlebar Templates in Apache Cordova

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

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));
    });
}

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

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.

Rob Gravelle
Rob Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured