PhoneGap templating with Mustache & jQuery

A useful habit to pick up somewhere along the road is templating. In this case, we will use the mustache.js templating engine, which can be used in a HTML & JavaScript setting. Templates consist of html containing {{variablename}} tags. The proposed solution (which uses jQuery) loads each templates from a separate file, which I find useful to keep things modular as well as orderly. Loading templates from separate files makes specifically sense in a PhoneGap setup, but works just as well in the browser, although in the latter case one often can reside to server-sided templating (or at least merge the separate template files into the main html file to prevent excessive http requests).

Note for testing: my Chrome browser threw some cross domain issues when testing this locally through the file:/// uri. For me (Ubuntu) the solution was to close Chrome and restart from the command line: google-chrome –new-window –allow-file-access-from-files file:///..


Let us start with a very simple file under tpl/test.tpl (relative to your index.html file) (create the tpl folder yourself).

Next, download mustache.j, throw it into your project and link it from your html file:

JavaScript – Loading the templates

Here’s a function you can use to load all your templates into (string) variables at once.

We load each file through an ajax request, and force jQuery to interpret the result as (plain) html. Note that we enforce synchronous loading: the script blocks until the template is loaded before continuing with the next template. This way we don’t have to worry about semi-loaded templates when the script continues.

This function could be called from jQuery’s document ready function:

JavaScript – Rendering a template

To render a mustache template, simply feed it with a structure that contains data fields that correspond to the {{fieldname}} tags in the template. These will then simply be replaced. The resulting html can be used to build your page, for instance with jQuery’s .html() command:

Wrap up and further ideas

From here on, you can make more, and more complex templates. You might also want to introduce better error handling / recovering. And when you have many templates, it may be an option to do partial loading or even loading on demand.


Leave a Reply

Your email address will not be published.