Object JavaScript – Templates Rendering JSON Using Mustache, jQuery


In our previous posts, you see how you can create templates and load them asynchronously using Knockout. But not everyone needs Knockout’s functionality. Maybe you just want to get some data and display it using a template.

Mustache is a library that allows you to read in JSON formatted data and display it using templates you design.

Mustache can be used for HTML, config files, source code – anything. It works by expanding tags in a template using values provided in a hash or object.

If you know JSON and a bit of JavaScript, you can implement Mustache. It is available for Ruby, JavaScript, Python, Erlang, PHP, Perl, Objective-C, Java, .NET, Android, C++, Go, Lua, ooc, ActionScript, ColdFusion, Scala, Clojure, Fantom, CoffeeScript, D, and for node.js.

In this tutorial, you’ll learn how to use Mustache with JavaScript to create HTML page.

Mustache is logic-less because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values.

Mustache provides the same functionality to libraries like underscore.js, handlebars.js, and dust.js.

Let’s start with an example by taking some JSON and converting it into some HTML.

Mustache Example

Let’s start with some JSON:

Start with a Mustache template:

You get this rendering:

You can try out this Mustache live demo and change it to your own code on GitHub.

Getting Started with Mustache

There are several ways to get Mustache.



Additional Requirements for Getting Started for Your Tutorial

In the example for the tutorial you will need a way to load in data, so you will use jQuery. You can get jQuery from one of these locations:

NOTE: You might have a problem when trying to read the JSON document if you don’t put this code on a server. For security reasons certain browsers (Google Chrome) don’t allow you to load external files on local folders. Those using Visual Studio are already using a server and can use any installed of the browsers.

Example Using Mustache.to_html()

Mustache need data and a template. The data is JSON. The template uses mustaches, names of the field we want to replace with our data in JSON, surrounded by mustache bars. Surrounding the mustaches is regular HTML.

You use the to_html method to take the template and data and convert it to HTML

In the following example you put data from a data file into a template using data binding. In order to loop through each of the products, use {{#products}} key tag , which specifies the name of the array containing all of the products to begin the loop.  and {{/products}} to end the loop.

Inside the loop, you can get the product name, category, and price and place them into a list item using their variable key tag.

<li>{{name}} {{category}} {{price}}</li>

The template ends up looking like this:

  {{#<li>{{name}} {{category}} {{price}}</li>

Use that template and the data with a call to the Mustache.to_html method from mustache.js to merge the template and the JSON data and return HTML.

The following example provides the data into a template defined in a variable.

Example Using a Script Template and External Data

Instead of using code to generate the template, we put the template into a script template.

First, create a Data folder, then put our JSON data into a text file, products.txt:

Next, create the container where mustache will render the results in the body tag.


Then add your template:

If the products key exists and has a non-false value, the HTML between the pound and slash will be rendered and displayed one or more times.

When the value is a non-empty list, the text in the block will be displayed once for each item in the list. The context of the block will be set to the current item for each iteration.

Next, load the data using jQuery.getJSON, and in the success callback, get the template using its id, apply the data you just received, and render the result to sampleArea.

So now… your entire page looks like this:

The result is


We have seen how we can separate how you can separate the display of data, from the main business logic.

More About Mustache

You have seen how Mustache uses tags to show a variable. {{person}} is a tag, as is {{#person}}. In both examples, you should refer to person as the key or tag key.

Triple Mustaches

All variables are HTML escaped by default. If you want to return unescaped HTML, use the triple mustache: {{{name}}}.

For example, with new template:

Will render:


Note that in the first description that had two mustaches, you see the escaped version. In the second, with triple mustaches, you see the HTML rendered.

False Values or Empty Lists

If a key tag exists, but had a value of false or empty list, then the HTML between the # and the slash will not be displayed.

With the following data:

And the following template:

Nothing will be rendered concerning stores tag. “Nothing shown here” would not appear.

But what if you did want to show something? You would use an Inverted Section that begins with a caret (hat) and ends with a slash. Inverted sections may render text once based on the inverse value of the key.



The Mustache Template Manual

Introduction to JavaScript Templating with Mustache.js

One comment

  1. Pingback: Single Page App – Using RequireJS Asynchronous Module Definition (AMD) Modules with jQuery, LoDash | DevDays®