How to use Mustache with JS / jQuery – a working example

I’ve been evaluating Mustache as a Javascript templating engine because my manager didn’t like the look of my jQuery code with lots of concatenation of HTML with javascript variables. The Mustache documentation doesn’t give working Javascript / jQuery examples so once I got this working it seemed only right to share it with you all (and hopefully drive a bit more traffic to my blog).

You can see the working page here and view the source code directly or view the listings below. It should be fairly self explanatory.

The main thing to understand is the you need to use something like jQuery’s $.get() function to import the template and $.getJSON to import the template data from a remote server. Template data is formulated into the correct mustache-like structure by the PHP (or other server-side language) layer.

The jQuery ( JSmustacheDemo.js ):

	var tmpl, 	// Main template HTML
	tdata = {}	// JSON data object that feeds the template
	// Initialise page
	var initPage = function(){
		// Load the HTML template
				tmpl = d
		// Retrieve the server data and then initialise the page	
		// When AJAX calls are complete parse the template 
		// replacing mustache tags with vars
			var renderedPage = Mustache.to_html( tmpl, tdata )
			$("body").html( renderedPage );

The PHP ( Tdata.php ):

class Tdata {
	public $locations = array(
			"label" => "New York City Zone 12, New York",
			"country" => "US",
			"label" => "East Boston, Massachssets",
			"country" => "US",
			"label" => "Compton, Los Angeles",
			"country" => "US",
			"label" => "Lisbon, Portugal",
			"country" => "PT",
echo json_encode( new Tdata() );

The Main HTML page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" tal:attributes="xml:lang language; lang language; dir reading_direction">
	<title>JS-Mustache Demo</title>
	<!-- Meta -->
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<!-- Stylesheets -->
	<link rel="stylesheet" href="style.css" type="text/css" />
	<!-- javascripts -->
	<script src="" type="text/javascript"> </script>
	<script src="mustache.js" type="text/javascript"></script>
	<script src="JSmustacheDemo.js" type="text/javascript"></script>		

The Template (template.html):

<div id="location_tabs">
	<ul id="list_locations">
			<li class="listItem_location">
				<img src="flags/{{country}}.png" class="flag_sm" />


  • It is possible to put the template HTML containing the {{mustache}} tags within the main HTML page (index.html), however when you do something like this,
    <img src="{{myimage}}" />

    … and then try to grab the template as a string,

    var templ = $("body").html()

    most browsers will HTML encode the mustache delimiters and you’ll get this returned to your script and your browser will throw an error because it can’t find the image:

     <img src="%7B%7BmyImage%7D%7D" />
  • Partials can be used for fragments of the template that need to be re-used and dynamically inserted. Here’s an example:
    	var tmpl = '<ul id="list_locations">{{#locations}}{{> locationTab}}{{/locations}}</ul>',
    	partials = {
    		locationTab : '<li class="listItem_location">{{label}}</li>'
    	tData = {
    		locations : [
    			{ label: "Manchester" },
    			{ label: "Nottingham" },
    			{ label: "London" }
    	// Initialise page
    	var initPage = function(){
    		$("body").html( Mustache.to_html( tmpl, tData, partials ) );

    Note: partials need to be passed to Mustache’s to_html() function as the third argument. Unlike the main template argument (the first arg) which is a single string containing the principle HTML tempalte, the partials object is an associative array of template strings, each one containing a separate template fragment.

If you liked this post then please comment and / or click on one of the google ads in the header.

3 thoughts on “How to use Mustache with JS / jQuery – a working example

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>