If you’ve been writing client side code for more than 15 minutes, you have likely had to consume and present JSON data. This is becoming a common scenario for front-end web developers.
The problem is that in most cases, you are inserting the return values into the same markup. So this means that you might be writing your own for-loops and element creation functions. But even with the help of the mighty jQuery, this can get tedious. More importantly, you are likely writing the same code more than once, each time customizing it for the specific situation. Well, regardless of the details, if this even partially describes some of the challenges you have faced lately, then it is likely that a client-side templating solution is needed.
Enter Mustache.js
Mustache.js is a lightweight JavaScript library that provides client-side templating. The feature-set is intentionally small. While some may see this as a drawback, I agree with their approach. The footprint is so small, that it is really a non-issue when it comes to considering the additional HTTP request (and you can, of course, concatenate it to your main JS file if you so choose). Websites such as Twitter, CNN and eBay, Inc. have turned to this JavaScript library, which is a testament to its power and usefulness.
The syntax is pretty simple
1 2 |
var foo = Mustache.render(TEMPLATE,DATA); document.getElementById(SOME-ELEMENT).appendChild(foo); |
TEMPLATE = Your HTML code with {{VALUE}} placeholders
DATA = Your JSON Data
Example # 1
1 2 3 4 5 6 7 8 9 10 |
(function(){ //pass a template and some JSON data to Mustache.js var output = Mustache.render("{{name}}<br />{{city}}",{ "name": "Joe Smith", "city": "London" }); //append the HTML that Mustache.js has created to the DOM $('#container').append(output); })(); |
Here is the fully-working JSFiddle.net link for Example # 1: http://jsfiddle.net/MsuPp/
In Example # 1, we call the render() method, which is a static member of the Mustache object. This method takes two arguments: the templated markup and the JSON data. This is not the most efficient way to utilize the method, but it is a good way to demonstrate how simple it is. Just create your HTML wtih the {{tag}} syntax where you want your output, and provide some data. Then use jQuery to append the return value of this method call to the element with the id of “container”.
Example # 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<!-- this is the HTML template --> <script type="text/html" id="template"> <h1>My Favorite European Cities</h1> <ul> {{#cities}} <li>{{name}}</li> {{/cities}} </ul> </script> <!-- this div is empty on page load --> <div id="container"></div> <script> (function(){ //this is our JSON (data) var data = { "cities": [ {"name": "London"}, {"name": "Paris"}, {"name": "Munich"} ] }, //get a reference to our HTML template template = $('#template').html(), //tell Mustache.js to iterate through the JSON and insert the data into the HTML template output = Mustache.render(template, data); //append the HTML template to the DOM $('#container').append(output); })(); </script> |
Here is the fully-working JSFiddle.net link for Example # 2: http://jsfiddle.net/WhxMa/2/
In Example # 2, we use a slightly more advanced approach. First, note the SCRIPT tag with the id of “template”. Instead of giving the type attribute a value of “text/javascript”, we use type=”text/html”. Since this makes no sense to the browser, the text node inside of the SCRIPT tags is ignored. But at the same time, that same text is available to us, so it is a great place to store template markup.
Inside of this SCRIPT tag, we have the opening and closing {{#cities}}{{/cities}} placeholders. This is used as a loop. What it does is tell Mustache.js: “Hey for each one of the elements in the ‘cities’ array, populate the markup accordingly.” So, Mustache.js iterates over that same markup for each element in the “cities” array, and inserts the value of cities[“name”] where the {{name}} placeholder appears.
Summary
These example are very basic and there is much more to dive into with Mustache.js. My hope is that this post has provided an overview that, at minimum, helps you to begin understanding and implementing this library.
Helpful Links for Mustache.js
https://github.com/janl/mustache.js/
http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-using-the-mustache-template-library/
[…] an earlier post: “Mustache.js – The Absolute Basics“, we learned how easy it is to leverage Mustache.js for simple, yet powerful client-side […]