Webessence

Javascript templating

A slightly modified version of John Resigs brilliant script JavaScript Micro-Templating. The modifications are:

  • Replace most of the regular expressions by splits, so it is easier to understand (at least for me) and it looks to be just as fast as the original.
  • I added an AJAX handler, so you can have external templates compiled on the fly.
  • Some refactoring, like the cache and the way it gets the template (by ID or by AJAX).

See the script tpl.js.

Template

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.

Javascript | 2011-11-19 10:32:43 | Comments (2)

Comments

Carl wrote on 2011-11-26 20:40:12

Cool, Resig is a genius but sometimes hard to follow. Your implementation is much easier.

Regina wrote on 2012-01-16 08:51:02

The blog is cool

Comments are turned off after 90 days.