A slightly modified version of John Resigs brilliant script JavaScript Micro-Templating. The modifications are:
See the script tpl.js.
A template is HTML with Javascript inside it. Javascript stands starts with <% and ends with %>. If you want the output of a Javascript variable, use <%=.
An internal template is embedded inside the HTML file and is surrounded by SCRIPT tags with an ID. It looks like this:
<script type="text/html" id="users_tpl">
<h3>Users from embedded template</h3>
<p><%=(new Date()).toString()%></p>
<ul id="tplId">
<% for ( var i = 0; i < users.length; i++ ) { %>
<% if (users[i].inActive) { continue; } %>
<li id="user<%=i%>"><%=users[i].name%> (<a href="<%=users[i].url%>"><%=users[i].url%></a>)</li>
<% } %>
</ul>
</script>An external template looks just like the internal one, except it isn't surrounded by SCRIPT tags.
To parse this template and add it to the HTML document, first include the template script and then:
// Get some data (this will problably be an AJAX JSON request)...
var data = [
{"name" : "Michael", "url" : "http://www.webessence.nl"},
{"name" : "Anthony", "url" : "http://www.quirksmode.org"},
{"name" : "Justin", "url" : "", "inActive" : true}
];
var dataObject = {"users" : data};
// An internal template
myTpl.$("someId").innerHTML = myTpl.tplById("users_tpl", dataObject);
To get an external template ("users.tpl.html") with an AJAX call:
// External template
myTpl.tplByAjax("users.tpl.html", dataObject, function(tplFunction, dataObjectArg) {
myTpl.$("someId").innerHTML = tplFunction(dataObjectArg);
});
See the demo.
Comments
Cool, Resig is a genius but sometimes hard to follow. Your implementation is much easier.
The blog is cool