Easy Templating with Mustache.js

Introduction

Any web development dude who is worth their salt would say to you
that you have to separate presentation code from logic code. That’s
why MVC, templating , MVP, MVVM and other acronyms where created.
Why separate presentation and logic?
To make code more maintainable and pleasing to the eyes of the
poor soul whose reading your code. Here’s an example of code that doesn’t use
templating:


var anime = {
	'cool' : [
		'onepiece','k-on','bleach','naruto','hanasaku iroha','star driver','yuru yuri','a channel','tari tari','sword art online','durarara'
	]
};
var parent = $('#no_templates'); //get the element where we are going to append things
var h1 = $('<h1>').text('Without templating'); //create a header
var ul = $('<ul>'); //create a ul element

h1.appendTo(parent); //append header to the no_templates div
ul.appendTo(parent); //append ul to the no_templates div

for(var x in anime.cool){
//append list item into the list
var li = $('<li>').text(anime.cool[x]).appendTo(ul);
}

What the code above does is simply to loop over a list cool anime and append each of them in an onordered list.
Ugly isn’t it?

In this tutorial I’m going to introduce to you a templating library
called Mustache. Mustache is available in
a variety of languages including PHP, Ruby, Python, Clojure, Node.js, ActionScript, and of course
JavaScript which is the flavor that were gonna be using today.

So yeah, go ahead and download Mustache.js from Github then include it into your page. As you might have noticed from the code a moment ago
I also used jQuery to make the code shorter and easier to write. So if you don’t have it yet you can either go to the jQuery site and download your copy or select jQuery 1.7.1 from this site. Later versions might also work.


<script type="text/javascript" src="mustache.js"></script><!--include mustache-->
<script type="text/javascript" src="jquery171.js"></script><!--include jQuery-->

Playing


Basics

To use mustache you must have a data source. This can be an array, a JSON string, a variable. Pretty much these are all objects in JavaScript so I’ll just go ahead and use the term object as a data source for mustache. Another thing that you’re going to need is a template which is basically HTML code where you specify how your data will be rendered in the page. For example if you want something to be displayed as a header the template is where you do it.
Lastly, you’re going to need an HTML element where you want to show your data.
That is all you need when using mustache. A data source , a template, and an HTML element where you want to show your data. Here’s an example:


<script type="text/javascript">
//define an object
var obj = {
		search : 'google',
		sites : ['google', 'twitter', 'facebook']
	};

var template = "<h1>Search Engine:{{search}}</h1>"; //define the template
var html = Mustache.to_html(template, obj); //put the data into the template
$('#container').html(html); //update the container div

</script>
<div id="container"></div>
<pre>

For your template code you just need to place the name of the property that you want to output in a specific tag. In this case the name of the property is search with the value of google. The value is the one that’s going to be rendered inside your template. So the code above will output the word google inside h1 tags.

Next I’m going to show you how to use sections. In programming terms sections are similar to the repeated portion of a loop. In sections we specify a start and an end and the portion that goes between the start and end is the repeated part based on the value of the current item. Here’s how to define a section (were using the same object from earlier):


var template = "<ul>{{#sites}}<li>{{.}}</li>{{/sites}}</ul>"; 

var html = Mustache.to_html(template, obj); //put the data into the template
$('#container').html(html); //update the container div

Let’s break it down. {{#sites}} define the start of the section {{/sites}} define its end. So the pound sign(#) defines the start and the forward-slash(/) defines the end. In between we put some
li tags because they’re basically repeated. Just remember that anything that is supposed to be repeated goes inside the section definition. Lastly we have this weird double mustache with a dot inside ({{.}}) which simply refers to the current item in the list.

Going Deeper


A cleaner way of writing templates

Were done with the basics now let’s try to go deeper. If you think defining templates this way is still ugly you’re not alone I think it’s also ugly. You might have notice that you can’t also go another line when defining templates like we did earlier. You’ll get a nasty error and you need to use plus(+) symbols to append stuff if your template becomes longer than the Golden Gate bridge.


var template = "<ul>{{#sites}}<li>{{.}}</li>{{/sites}}</ul>";

Well good news for you since there’s actually another way of defining a template all you have to do is to place your template inside tags but with the
type of text/html instead of the usual text/javascript which we don’t even need when using html5. Here’s an example:

<script id="anime" type="text/html">
<ul>
	{{#watched}}
	<li>{{.}}</li>
	{{/watched}}
</ul>
</script>

And there’s a bit difference in the code for assigning the data source into the template. Examine the code below:

<script type="text/javascript">
var anime = {
			'watched' : [
						'onepiece','k-on','bleach','naruto',
						'hanasaku iroha','star driver','yuru yuri',
						'a channel','tari tari','sword art online','durarara'
			]
		};

var html = Mustache.to_html($('#anime').html(), anime);
$('#container').html(html);
</script>

<div id="container"></div>

As you might have notice we changed this part of the code to use the template that we have created earlier. All you have to do is to select it using a css selector in this case were selecting the template with the id of anime.

var html = Mustache.to_html($('#anime').html(), anime);


A different structure for data source

Were fine with how the data source is structured so far. But what if our data source is structured in a different way? In some cases we have to deal with data coming from other websites like twitter or facebook for displaying tweets or status updates from users. Data is not always structured the way we like it. In this part I’ll try to walk you through some of ways in which data can be structured and show you how to place them in our mustache templates.
As you can see from the code below we have some repeated properties in our object. This will affect the way on how we will access them on our template later on.

<script type="text/javascript">
var ind = {
	'people' : [
		{'name' : 'kyoya', 'age' : 20, 'dialect' : 'kansai'},
		{'name' : 'pedro', 'age' : 30, 'dialect' : 'tagalog'},
		{'name' : 'juan', 'age' : 15, 'dialect' : 'pangalatok'}
	],
	'languages' : [
		{'name' : 'php', 'author' : 'rasmus lerdorf'},
		{'name' : 'python', 'author' : 'guido van rosum'},
		{'name' : 'ruby', 'author' : 'yukihiro matsumoto'}
	]
};

	var html = Mustache.to_html($('#languages').html(), ind);
	$('#container').html(html);
</script>
<div id="container"></div>

Here’s the code for the template. For our data there are some repeated items namely the name, dialect, and the author. All we have to do is to place those repeated items inside of the section. If you remember when looping through an array we placed a period {{.}} this time we place the actual name of the item inside the section.

<script id="languages" type="text/html">

<h1>People</h1>

<ul>
	{{#people}}
	<li>
	Name: {{name}} 
	Age: {{age}}
	</li>
	{{/people}}</ul>
	
<hr/>
<h1>Languages</h1>

<ul>
	{{#languages}}
	<li>
	Name: {{name}} 
	Author: {{author}}
	</li>
	{{/languages}}
</ul>
</script>

There are also times when the data source is 3 or more properties deep such as this one:

<script type="text/javascript">
	var characters = {
		deep : {
			'DragonBall' : {
				'Characters' : ['goku', 'gohan', 'trunks', 'cell', 'vegeta'],
				'Techniques' : ['kame hame wave', 'instant transmission']
			},
			'Onepiece' : {
				'Characters' : ['luffy', 'ace', 'zoro', 'nami', 'usopp', 'sanji', 'franky', 'robin', 'brook'],
				'Techniques' : ['Diable Jambe', 'haki', 'hocho sabaki', 'fleur', 'asura']
			}
		}
	};

	var html = Mustache.to_html($('#characters').html(), characters);
	$('#container').html(html);
</script></pre>
<div id="container"></div>
<pre>

If that’s the case all you have to do is to use dot notation to access the properties that you want. Unfortunately bracket notation doesn’t seem to be working on Mustache so better stick with a naming convention that works with dot notation. Check out the JavaScript best practices from the JavaScript toolbox if you want to learn about names that works with dot notation. I’ve also linked to it in the resources section in case you’re far-sighted. Here’s how we access those properties from our template:

<script id="characters" type="text/html">

<h1>Onepiece Characters</h1>

<ul>
	{{#deep.Onepiece.Characters}}
	<li>{{.}}</li>
	{{/deep.Onepiece.Characters}}
</ul>

<h1>Onepiece Techniques</h1>
<ul>
	{{#deep.Onepiece.Techniques}}
	<li>{{.}}</li>
	{{/deep.Onepiece.Techniques}}
</ul>

</script>

Lastly I’m going to show you an example on how to use data from a remote source (let’s just pretend that its from a remote source) and use that data for our mustache templates. For this example were going to use PHP for the backend and some AJAX methods from jQuery (though it should be AJAJ- Asynchrounous JavaScript and JSON since were using JSON not XML, but yeah AJAX sounds nicer) to fetch the data from PHP.

First we’ll have to create a new PHP file (data.php) and then build the data using arrays. JavaScript flavored arrays to be exact. I’m using PHP 5.4 which is the latest version of PHP at the time of writing of this article. It’s always a good idea to use the latest version of a library, a framework or a programming language since there are lots of new features and benefits. More information about what’s new in PHP 5.4. Here are the contents of the php file that serves as our data source. As you can see were just using arrays and then convert it to JSON string using the json_encode() method in php. This is an important step since its easier to make use of JSON in JavaScript.

<?php $data = ['ninjas'=>[
			'naruto'=>['name'=>'naruto', 'skills'=>['rasengan', 'kage bunshin']],
			'sasuke'=>['name'=>'sasuke', 'skills'=>['chidori', 'sharingan']],
			'lee'=>['name'=>'lee', 'skills'=>['leaf hurricane', '5 gates']]
		]
		];

echo json_encode($data); //convert array to JSON string
?>

And we just fetch the data using the $.post method in jQuery. A quick and nice method for doing AJAX request in jQuery. It’s actually a convenience method for the $.ajax method to make life easier for our fingers that are tired from everyday coding.

<script type="text/javascript">
$.post('data.php', {}, function(data){
		var ninja = JSON.parse(data); //parse JSON string from PHP to convert it to an object
		var html = Mustache.to_html($('#ninja').html(), ninja);
		$('#content').html(html);
	});
</script>

<div id="content"></div>

And for the template we use the dot notation again to access the skills of each ninja. Remember to start with the root property which is ninjas:

<script id="ninja" type="text/html">
<h1>Naruto</h1>
<ul>
	{{#ninjas.naruto.skills}}
	<li>{{.}}</li>
	{{/ninjas.naruto.skills}}
</ul>

<h1>Sasuke</h1>

<ul>
	{{#ninjas.sasuke.skills}}
	<li>{{.}}</li>
	{{/ninjas.sasuke.skills}}
</ul>

<h1>Rock Lee</h1>

<ul>
	{{#ninjas.lee.skills}}
	<li>{{.}}</li>
	{{/ninjas.lee.skills}}
</ul>

</script>

Conclusion

So yeah I guess that’s it for this tutorial on how to use Mustache for templating. You’ve learned the basics of Mustache, how to access properties using the dot notation, using JSON data as a data source for your templates. I hope you learned something and please share this tutorial if you like it.

Resources

4 thoughts on “Easy Templating with Mustache.js

  1. Hi, I have a question. i just start using mustache.js library and i’m a little confuse how to understand this better. in my code when i execute the onClick function it show me the dialog box but without any content inside, just black screen. I think that i follow mustache idea in the wrong way and that’s way i don’t get it in the right way, can you just tell me what possible i’m doing wrong? i’m using an json external file as database.

    json file
    {
    “poult”: [
    {
    “name”: “text”,
    “shortname”: “pfrito”,
    “timer”: “3 Min”,
    “portion”: “4 Part”,
    “popup”: [
    {“shortname”: “pfrito”},
    {“descn”: “text here”},
    {“notes”: “another text.”},
    {“ingn”: “more text”},
    {“notn”: “note of my text”}
    ]
    }
    ]
    }
    ———————-
    template

    {{#poult}}

    {{timer}}
    {{portion}}
    Details

    {{name}}

    {{/poult}}

    {{#popup}}

    Ingredients:
    {{ingn}}

    Preparation:
    {{descn}}

    Note
    {{notn}}

    {{/popup}}

    ———————-
    the js get function to call json file
    $.getJSON(‘poultrys.json’, function(data) {
    var template = $(‘#recipestpl’).html();
    var html = Mustache.to_html(template, data);
    $(‘#group’).html(html);
    });

    i would like to know what i’m missing or if i missing all?

    thanks for any help

    mbarcala

    • first you have to verify if your json file is actually returning a valid json string. You can convert it to a javascript object using JSON.parse(data). If its converted without problems then its valid. It seems like there’s no problem with your template either and the way you assigned your data to your template so its probably your json file that’s causing the problem.

Leave a comment