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 ):
$(function(){ var tmpl, // Main template HTML tdata = {} // JSON data object that feeds the template // Initialise page var initPage = function(){ // Load the HTML template $.get( 'template.html', function(d){ tmpl = d } ) // Retrieve the server data and then initialise the page $.getJSON( "Tdata.php", function(d){ $.extend(tdata,d); } ) // When AJAX calls are complete parse the template // replacing mustache tags with vars $(document).ajaxStop(function(){ var renderedPage = Mustache.to_html( tmpl, tdata ) $("body").html( renderedPage ); }) }() }) |
The PHP ( Tdata.php ):
<?php class Tdata { public $locations = array( array( "label" => "New York City Zone 12, New York", "country" => "US", ), array( "label" => "East Boston, Massachssets", "country" => "US", ), array( "label" => "Compton, Los Angeles", "country" => "US", ), array( "label" => "Lisbon, Portugal", "country" => "PT", ), ); }; echo json_encode( new Tdata() ); ?> |
The Main HTML page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" tal:attributes="xml:lang language; lang language; dir reading_direction"> <head> <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="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"> </script> <script src="mustache.js" type="text/javascript"></script> <script src="JSmustacheDemo.js" type="text/javascript"></script> </head> <body></body> </html> |
The Template (template.html):
<div id="location_tabs"> <ul id="list_locations"> {{#locations}} <li class="listItem_location"> <img src="flags/{{country}}.png" class="flag_sm" /> {{label}} </li> {{/locations}} </ul> </div> |
Notes
- 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:
$(function(){ 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.
Thanks for this nice run down!
btw. Do you know if the “” issue has or will be solved? It seems that the Gurus that be use inline templating (https://vimeo.com/26147136) so there must be a way around it.
Thanx for the post – I needed a simply getting started example for mustache and jquery -
Why didn’t you used the jquery port of mutache?
LT
Brilliant! I’m going to bookmark this and get something working for my employer today, I hope. Your article is very straightforward and easy to understand.