andrew.hedges.name / blog

Introducing jQuery Simple Templates

3 September 2008 · Estimated reading time: 2 minutes

Overall, I love jQuery. One thing I have missed from my Prototype days was simple, built-in templating. Introducing jQuery Simple Templates.

I’ve been meaning to write a blog post about jQuery for a while. If you’re a web developer, you’d have to have been living under a rock for the past year not to have heard about it. jQuery is billed as the “write less, do more” JavaScript framework, and I have to say I agree.

Get Simple Templates

That said, one deficiency in jQuery has been nagging at me for a while. When I was doing a lot of work with Prototype, I made extensive use of the Template class. As the name implies, it is a way to create re-usable strings that can be merged with values to produce something useful.

Here’s an example of templates in Prototype:

var link = new Template('[#{label}](#{url})');
var values = {
    url : 'https://andrew.hedges.name',
    label : 'My Homepage'
};
// [My Homepage](https://andrew.hedges.name)
alert(link.evaluate(values));

I wrote Simple Templates to work pretty much the same way. Here’s an example:

var link = '[#{label}](#{url})';
var values = {
    url : 'https://andrew.hedges.name',
    label : 'My Homepage'
};
// [My Homepage](https://andrew.hedges.name)
alert($.tmpl(link, values));

I’m pretty happy to have an easy way to do templating in jQuery without having to learn a new syntax. Maybe the best thing about this plug-in, though, is the fact it weighs in at only 1009 bytes!

Bug reports and enhancement requests can be filed at the project home on Google Code.

Enjoy!