Object JavaScript – Templates Rendering JSON Using Mustache, jQuery

mustachelogo

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:


{
"header": "this is my header",
"items": [
{"name": "red", "first": true, "url": "#Red"},
{"name": "green", "link": true, "url": "#Green"},
{"name": "blue", "link": true, "url": "#Blue"}
],
"empty": true
}

Start with a Mustache template:


<h1>{{header}}</h1>
{{#bug}}
{{/bug}}
{{#items}}
{{#first}}
<li><strong>{{name}}</strong></li>
{{/first}}
{{#link}}
<li><a href="{{url}}">{{name}}</a></li>
{{/link}}
{{/items}}
{{#empty}}
<p>The list is empty.</p>
{{/empty}}

You get this rendering:


<h1>this is my header</h1>
<li><strong>red</strong></li>
<li><a href="#Green">green</a></li>
<li><a href="#Blue">blue</a></li>
<p>The list is empty.</p>

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.

image

 

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:

Products:
<ul>
  {{#products}}
  {{#<li>{{name}} {{category}} {{price}}</li>
  {{#{{/products}}
</ul>

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.


<!DOCTYPE html>
<html>
<head>
<title>Mustache</title>
</head>
<body>
<div class="main-content">
<div>
<h1>All Products</h1>
<ul id="products"></ul>
</div>
</div>
<div id="sampleArea"></div>
<script src="Scripts/jquery-2.0.2.min.js"></script>
<script src="Scripts/mustache.js"></script>
<script>
var data = {
products: [
{
id: 1,
name: "Toy1",
category: "Toy",
price: 45.03,
freshness: new Date()
},
{
id: 2,
name: "Toy2",
category: "Toy",
price: 35.20,
freshness: new Date()
}
]
};
console.log(JSON.stringify(data));
var template = "Products:<ul>{{#products}}" +
"<li>{{name}} {{category}} {{price}}</li>" +
"{{/products}}</ul>";
var html = Mustache.to_html(template, data);
$('#sampleArea').html(html);
</script>
</body>
</html>

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:


{
"products": [
{
"id": 1,
"name": "Toy1",
"category": "Toy",
"price": 45.05,
"description": "<p>This is <strong>strong</strong> description Toy1</p>"
},
{
"id": 2,
"name": "Toy2",
"category": "Toy",
"price": 35.20,
"description": "<p>This is an <em>emphasis</em> description of Toy2</p>"
}
]
}

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

https://gist.github.com/devdays/6a2017e0594c5fefbd6f

Then add your template:


<script id="productTmpl" type="text/template">
Products:
<ul>
{{#products}}
<li>{{name}} {{category}} {{price}}</li>
{{/products}}
</ul>
</script>

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.


<script src="Scripts/jquery-2.0.2.min.js"></script>
<script src="Scripts/mustache.js"></script>
<script>
var data = {};
$.getJSON(
"Data/products.txt",
function (d) {
data = d;
var template = $("#productTmpl").html();
var html = Mustache.to_html(template, data);
$('#sampleArea').html(html);
}
);
</script>

So now… your entire page looks like this:


<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="main-content">
<h1>All Products</h1>
<div id="sampleArea"></div>
</div>
<script id="productTmpl" type="text/template">
Products:
<ul>
{{#products}}
<li>{{name}} {{category}} {{price}}</li>
{{/products}}
</ul>
</script>
<script src="Scripts/jquery-2.0.2.min.js"></script>
<script src="Scripts/mustache.js"></script>
<script>
var data = {};
data.products = {};
$.getJSON(
"Data/products.txt",
function (d) {
data = d;
var template = $("#productTmpl").html();
var html = Mustache.to_html(template, data);
$('#sampleArea').html(html);
}
);
</script>
</body>
</html>

The result is

image

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:


<script id="productTmpl" type="text/template">
Products:
<ul>
{{#products}}
<li>{{name}} {{category}} {{price}}<br />
{{description}}<br />
{{{description}}}
</li>
{{/products}}
</ul>
</script>

Will render:

image

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:


{
"stores": false
}

And the following template:


<script id="storesTmpl" type="text/template">
<ul>
{{#stores}}
Nothing shown here
{{/stores}}
{{^stores}}
No stores open.
{{/stores}}
</ul>
</script>

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.

image

References

The Mustache Template Manual

Introduction to JavaScript Templating with Mustache.js


One thought on “Object JavaScript – Templates Rendering JSON Using Mustache, jQuery

Comments are closed.