We have launched our new Privacy Policy. You can read more about it here.

Quick Tip: An Introduction to jQuery Templating


JavaScript Templating is a neat idea: it allows you to easily convert JSON to HTML without having to parse it. At Microsoft's MIX10 conference, they announced that they are starting to contribute to the jQuery team. One of their efforts is to provide a templating plugin. In this quick tip, I'll show you how to use it!

You'll need the data to template; you'll likely retrieve JSON from your server; of course, Object / Array literals work just as well, so that's what we use:

The template is written in <script type="text/html"></script> tags; for each item in your JSON, the template will render the HTML; then, it will return the entire HTML fragment to you. We can get to the JavaScript values from within the template by using {% and %} as tags. We can also execute regular JavaScript within these tags. Here's our template:

To render the data with the template, call the plugin; pass the data to the plugin method; you can optionally pass in an options object as well. (These aren't predefined options; they're values you want to use within the template, perhaps for branching.)

It's that easy! Have fun with it! You can get the complete code for this quick tip on Github