Movember ; the time to learn about Mustache.js
Mustache.js is a tempting engine for Javascript, and I thought since it was “Movember”, it was time to learn how to use it.
All Mustache.js does is tidy up spaghetti code that can result from rendering json objects as HTML
i.e. strHtml += “<div …..>” + obj.name + “</div><div …><span …>’ + obj.value ‘</span></td>’;
and all that yuckiness.
So here is a simple Hello World – type example, with an externalised template for extra neatness.
<html>
<head>
<script src=”http://code.jquery.com/jquery-1.10.1.min.js”></script>
<script src=”http://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.7.2/mustache.js”></script>
</head>
<body>
<script language=”javascript”>
var person = {
firstName: “Christophe”,
lastName: “Coenraets”,
blogURL: “http://coenraets.org”
};
$(init);
function init()
{
var template = $(‘#personTpl’).html();
var html = Mustache.to_html(template, person);
$(‘#sampleArea’).html(html);
}
</script>
<div id=”sampleArea”></div>
<script id=”personTpl” type=”text/template”>
<h1>{{firstName}} {{lastName}}</h1>
<p>Blog URL: <a href=”{{blogURL}}”>{{blogURL}}</a></p>
</script>
</body>
</html>