Quick Tip: An Introduction to jQuery Templating

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:

var data = [
		{ name : "John",  age : 25 },
		{ name : "Jane",  age : 49 },
		{ name : "Jim",   age : 31 },
		{ name : "Julie", age : 39 },
		{ name : "Joe",   age : 19 },
		{ name : "Jack",  age : 48 }
	];

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:

<li>
	<span>{%= $i + 1 %}</span>
	<p><strong>Name: </strong> {%= name %}</p>
	{% if ($context.options.showAge) {  %}
		<p><strong>Age: </strong> {%= age %}</p>
	{% } %}
</li>

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.)

$("#listTemplate").render(data, { showAge : true }).appendTo("ul");

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



Leave a Reply

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