
jQuery Templates : Create, Compile, Cache and Render
So the new official jQuery plug-ins developed by Microsoft has been released a couple of days ago and I for one am very excited. The release consists of a trio of plugins, the jQuery Template plugin, jQuery DataLink as well as jQuery Globalization. I attended a online conference a month or so ago where Rey Bango (@reybango) introduced jQuery Templates. Throughout the talk I went from loving it, to not being sure about it but, in the end I was converted and, having played with jQuery templates now for some time I do feel this is a move in the right direction.
In this first article regarding the new plug-ins I will be giving you a quick introduction to the jQuery Template plugin. I guess the first question would be, what does a jQuery Template look like:
<script id="myTemplate" type="text/x-jquery-tmpl">
<li><strong>${Name}</strong> was released in ${ReleaseYear}</li>
</script>
If you have used any template frameworks such as Rails or Mustache the above will look very familiar. The one thing that might be a little unclear is why the template is defined inside a script tag and why you specify the type as text/x-jquery-tmpl. Technically you can use any tag such as, for example, a div with a CSS property of display:none but, due to the possibility of triggering unexpected behavior as the browser will parse the content of the div and make it part of the DOM, it is suggested that you stick with the script tag. The reason for specifying the text/x-jquery-tmpl value is simply because the browser will not understand this type and therefore not try to parse or render the content and simply treat it as text.
Let’s put this template to use. We are going to pull some data from Netflix using their oData Catalog API and display it using a jQuery Template. Go ahead and create a new HTML page with the following structure:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Netflix oCatalog API with jQuery Templates</title> </head> <body> </body> </html>
To the body of the document add the following:
<article id="movie_list_container"> <h1>Horror Movies from the 70's</h1> <dl id="movieList"></dl> </article>
Next, let’s add the code that will load the information we want to display from Netflix:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
$().ready(function() {
$.ajax({
dataType: "jsonp",
url: "http://odata.netflix.com/Catalog/Genres('Horror')/Titles?$filter=ReleaseYear%20le%201979%20and%20ReleaseYear%20ge%201970&$format=json",
jsonp: "$callback",
success: function(data){
}
});
});
Now that we have out HTML and our Ajax call set-up, we need to download the jQuery Template plugin and include it inside our project and HTML file. You can download the latest version of the official plugin from Github. Once you have downloaded the plugin and extracted it, copy the file jquery.tmpl.min.js to your project directory. Next add this file just after the line where you import jQuery:
<script src="js/jquery.tmpl.min.js"></script>
With this we are ready to add our template and render our content. Add the following inside the definition list in your HTML:
<script id="movieListTmpl" type="text/x-jquery-tmpl">
<dt><strong>${Name}</strong> : ${ReleaseYear} : <a href="${Url}">View on NetFlix</a></dt>
<dd>{{html Synopsis}}</dd>
</script>
The above is then our jQuery Template and you can clearly see where we will be injecting the data returned from Netflix. The variable names I use above is not defined somewhere in the JavaScript or inside the template, these simply map to the keys inside the JSON object. You can examine each object returned by Neflix by logging the JSON object to the console and taking a look at it inside Firebug or Web Inspector. To do this add the following inside the success callback:
console.log(data.d.results);
If you loaded the page now, you will see the JSON object returned logged to the console and you can expand these to take a look at the data it contains:

From the above you can see some of the keys we are going to use such as ‘Synopsis’ and ‘URL’. Other then the information being logged to the console you page will still be empty. There is one step left and that is to push the data to our template. To do this, replace the console.log with the following:
$("#movieListTmpl").tmpl(data.d.results).appendTo("#movieList");
With the one liner above you are done. First we start of by specifying the template we want to use, using the id selector. Next we call the tmpl() function on the returned object and pass in the data. The tmpl() function accepts two parameters, the first being the data and the second being an optional map of user defined key-value pairs. Now, if the data you pass in is an Array, the template will be rendered once for each of the Objects in the array. If the data is a single Object, the data parameter is missing or null, the template will be rendered once.
Because of this, it does not matter whether the Netflix API returns a single JSON object or multiple. The last part of the above line simply tells jQuery where to inject the rendered template in the DOM. If you go ahead and load up the demo page now, you will see how jQuery Templates handles the returned data seamlessly. If you look at the synopsis, you will find that it renders the content as HTML this is because we are rendering the synopsis content differently to the other data items.
The content returned by Netflix for the Synopsis has some HTML in it, such as the links to actors etc., and displaying it as plain text would display the HTML tags instead of parsing the HTML data therefore, we using the {{html}} template tag to render the synopsis. I will be going to more detail on the different template tags and how to use them in my follow on article. With our content loading in via Ajax and displaying via our template, we are done. You can now style the content whichever way you want to make it look more interesting.
Before ending of today’s article I want to touch on some off the other base aspects of jQuery templates. In the sample above we used the tmpl() function and an inline template. It is also possible to load the template via an external JS file or even as a string via Ajax. When doing this you need to first compile your template before you can render it. To compile a template you use the following code:
$("#template").template("myTmpl");
/* Alternatively you can assign the return value to a variable */
var myTmpl = $("#template").template();
After you have included the line above, your template is compiled and cached and you can now use it using the name you defined. What do you think of the jQuery Template plugin? Do you feel it is a move in the right direction? Do you have a preference for another template framework? Looking forward to your comments.
