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.