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:
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:
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: