Let’s face it. We spend a lot of time writing markup in all sorts of languages. Whether we’re producing the next big social networking site or creating a funky template, there is a lot of boilerplate that is continuously repeated. More importantly, chances are we’re implementing it in a mix of JavaScript, HTML and our backend language of choice.
It makes managing our presentation a muddled mess. That’s where template engines come in. If you’re using pure PHP, you could use Smarty, but this is a JavaScript-focused blog and you probably have some of your presentation in pure JavaScript anyway.
That’s where mustache comes in. Available in most web languages, it provides a simple and flexible way of integrating content into your site.
Let’s say we’re implementing a receipt purely in JavaScript. Our data looks like this:
{
"title": "Our Web Store",
"items": [
{"name": "Widget",
"unitprice": "1.45",
"quantity": "2",
"totalprice": "2.90"
},
{"name": "Whosit & Whatsit",
"unitprice": "0.45",
"quantity": "1",
"totalprice": "0.90"
}
]
}
First, we’ll integrate the mustache library, like so:
<script type="text/javascript" src="mustache.js"></script>
Next, we’ll define the template:
var template = "<h1>{{title}}</h1>
{{#items}}
<dt<strong>{{name}}</strong></dt>
<dd>${{totalprice}}</dd>
<dt>{{quantity}} @ {{unitprice}}</dt><dd></dd>
{{/items}}";
Finally, we simply have to render the HTML, like so:
var html = Mustache.to_html(template, json);
This will produce output like:
<h1>Our Web Store</h1>
<dt><strong>Widget</strong></dt>
<dd>$2.90</dd>
<dt>2 @ 1.45</dt><dd></dd>
<dt><strong>Whosit & Whatsit</strong></dt>
<dd>$0.90</dd>
<dt>1 @ 0.45</dt><dd></dd>
You can then use your DOM manipulation technique of choice to insert the markup.
Note that it automatically escaped the ampersand. Had we used three curly brackets, then it would have allowed it to remain literal.
What happens when we items is an empty array or, worse, isn’t there at all? It simply doesn’t appear, because the hash prefix in our template makes it conditional. You can invert the condition (say, for presenting a special message for missing information) by using a caret (^).
Since the items element was actually an array, mustache also automatically knew to loop through, which could potentially be handy for commenting systems.