Archive for April, 2009:
JavaScriptTemplates (JST)
I started working with JavaScriptTemplates today after finding that jtemplates really let me down on performance on a long template (it was taking about 2.5s to load, JST topped at 200ms).
Just to give you a flavor for how it works, I’ll outline how I used it. To start, I created a JSON data file - typically this would be fed by a web service, but for getting up and running, a file is easy.
userdata.json:
{ users : [
{ name: "John Doe", email: "john.doe@nthread.com"},
{ name: "Jane Doe", email: "jane.doe@nthread.com"}
] }
Then I created a really basic web page. The page had a div where the templated HTML would be placed:
<div id=’userlist’ ></div>
And imported the jQuery & JST scripts in the header:
<script src=”scripts/jquery.min.js” type=”text/javascript”></script>
<script src=”scripts/trimpath-template.js” type=”text/javascript”></script>
Next, I created the template, which needs to be placed in a textarea. All of the templating libraries I have seen use a textarea for this, probably because it is the only place on a web page where you can avoid the browser parsing the HTML into DOM elements (which leads to escaping):
<textarea id='userlist_template' style='display:none' >
<ul>
{for user in users}
<li><a href='mailto:${user.email}' >${user.name}</a></li>
{/for}
</ul>
</textarea>
Finally, a small piece of JST & jQuery is used to load the JSON file in process it through the template:
<script type="text/javascript" >
$(document).ready(function() {
var data = $.getJSON("users.json", null, showData);
});
function showData(data) {
var userlistTemplate = TrimPath.parseDOMTemplate("userlist_template");
$("#userlist").html(userlistTemplate.process(data));
}
</script>
That’s really all there is to it. This prints out the fairly unexciting:
User List
It really is pretty cool though, try it out.
