Srender to Simple Javascript Templating

19 February, 2009


photo by kiddharma

jQuery brings web sites to life. It's great at getting data from services, capturing user interaction, manipulating web pages, etc. However, when you start building large swaths of the page from scratch based on javascript-resident data, it starts to be time for a real templating system.

That's when it's time to Srender.

Srender is a jQuery plugin for javascript templating adapted from John Resig's classic templating blog post. The code works mostly like Resig describes in that post with a few small changes. The usage is as follows:

var data = {foo : "bar"}
var template = "my data: <%= data.foo %>"
console.log($.srender(template, data));

If you pass it a jQuerified element as the optional third argument, it will populate that element with the results thusly:

var data = {foo : "bar"}
var template = "my data: <%= data.foo %>"
$.srender(template, data, $("h1"));

You can also iterate through objects, do other command structures, and basically just run real javascript from inside your templates:

var data = [1,2,3,4]
var template = (<r><![CDATA[
<% for ( var i = 0; i < data.length; i++ ) { %>
<% if(data[i] != 2 ){ %>
<li><%= data[i] %></li>
<% } %>
<% } %>
]]></r>).toString();
console.log($.srender(template, data));

E4X is a nice choice to give a heredoc-style syntax to the templates. For more on E4X, check out this excellent resource.

Or, if you're a sissy who runs a browser that can't handle E4X, the '' escaped new line syntax isn't too bad either:

var template = '<% for ( var i = 0; i < data.length; i++ ) { %>
<% if(data[i] != 2 ){ %>
<li><%= data[i] %></li>
<% } %>
<% } %>'

As usual, the code is on The Github: atduskgreg/srender. Patches and pull requests are welcome if you find any bugs or add any features. Many thanks to Resig for jQuery, this great templating hack, and the the general joy he spreads around the land of js development.

I'm using Srender along with another exciting piece of javascript code in a little side project I'm working on now. I hope to be ready to announce both the other mew library as well as the side project in the coming days so stay tuned!