Super simple jQuery templating

Working with jQuery, it is common to find yourself needing some kind of templating solution. There are plenty out there, however sometimes the use-case is simple enough that you don’t really need a fully blow templating plugin.

We’ll take a task list as an example (just to be original). Lets say you have the following task objects in an array:


var tasks = [
  { id: 1, name: 'A todo item' },
  { id: 2, name: 'Another todo' }
];

Now you want to display them in an unordered list with checkboxes etc. What I like to do is create a ‘templates’ object, which contains my basic templates:


var templates = {
  taskList: $('<ul class="task-list">'),
  taskItem: $('<li><input type="checkbox" /> <span /></li>')
}

With these templates in place, it’s a simple case of cloning them when required and inserting the relevant data. jQuery’s ‘text‘ and ‘attr‘ methods are ideal for this as they handle the escaping of html entities. Based on this we can iterate over our tasks array and insert the relevant items in the dom:


var list = templates.taskList.clone();
$.each(tasks, function() {
  templates.taskItem.clone()
    .attr('id', this.id)
    .find('span').text(this.name).end();
  list.append();
});

$('body').append(list);

And that’s it, by using jQuery’s ‘text‘ and ‘attr‘ functions, you have complete control over your templates, without having to remember to escape html. Your templates can be stored away in an external javascript file and everyone’s happy.

Published by

Jamie

Hi, I am the Managing Director of SonicIQ Limited in the UK. I have been working in the web development industry since 1999 and have been running SonicIQ since 2001. Currently Ruby On Rails is my preferred development platform. I am experienced in designing with web standards, HTML5, CSS3 and Javascript.

One thought on “Super simple jQuery templating”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>