May 112011

I came across this amazingly useful jquery feature at Microsoft Tech-ed 2011 at a talk by Fritz Onion. Microsoft for a long time now has been favoring jQuery instead of the in house developed Ajax Control Toolkit. Though both of them coexist for now in some of the ASP.NET Visual studio templates, I believe its only a matter of time before ACT is totally discarded as jQuery has proven to be the defacto web standard for Javascript programming.

Its also heartening to know that not only are Microsoft planning to adopt jQuery as the standard in their frameworks, they are also going to actively contribute code to the jQuery project. (To clarify, Its not a fork from the original project and jQuery will continue to be licensed under the MIT-PL). One such Microsoft initiative is the jQuery plugin – Templates. Its so useful and simple to use that I am amazed no one thought of this before.

jQuery Templates rids us the need for using DOM manipulation code while adding elements on the fly. It acts like a placeholder for certain pieces of data, the values of which are dynamically substituted by the plugin and also acts as a sort of repeater for multiple elements following the same data structure. I would call it a cross between the .NET String.Format() and HTML repeater control. For e.g. below is a sample template tag

There are two things that stand out in the above script tag, one is an unfamiliar type – x-jquery-tmpl and the other are the $ signs. Apart from that, the rest of the stuff is pretty much run-of-the-mill markup. The x-jquery-tmpl type is used to make the browser ignore the content between the script tag and not try to parse it. This is necessary since the parsing would need to be done by the plugin. The $ is used to mark the member name of the binding data structure. For e.g. ${genre} indicates that this value would be replaced by the genre property of the object that is bound to the template tag.

This is the script code which gets data from the server (an Xml file which contains a catalog root node with 12 book nodes and details like name, author, price etc) through an ajax call and then binds it to the template script tag which we described in the previous paragraph. The template needs an array of objects which have to bound to the individual tags. Any markup will be repeated the number of times as there are elements in the array.

* Description: JQuery Templating feature
* Author : Ganesh Ranganathan 
$(document).ready(function () {
    //Method to be called when all DOM elements are loaded

function makeAjaxCall() {
        url: 'ajax/catalog.xml', //Make an ajax call to the server
        datatype: 'xml',
        success: function (data) {
            // Callback function on successfull call
            var books = [];
            //Iterate through the xml file and apply function on each 'book' node
            $(data).find('book').each(function () {
                //books is an object array where we create an object for each xml node
                //and assign values to the properties. These property names are bound in
                //the templates
                books.push({ bookName: $(this).find('title').text(),
                author: $(this).find('author').text(),
                genre: $(this).find('genre').text(),
                price: $(this).find('price').text(),
                description: $(this).find('description').text()

        //This is the templating call where the data structure is bound to the id
        //of the script tag. The tmpl() call returns the DOM element containing the HTML
        // which is then appended to the mainDiv which is the holder element

This is the minimal markup that needs to be used for the page. The important part is the the script files – jquery.1.4.4.min.js and jquery.tmpl.js that can be downloaded from its repo on github or you could add a NuGet Package reference as well which auto adds all the dependencies and saves a lot of time.

<head runat="server">
    <script src="Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
    <script src="Scripts/jQuery.tmpl.js" type="text/javascript"></script>
    <script src="Scripts/script.js" type="text/javascript"></script>
    <link href="Styles/styles.css" rel="stylesheet" type="text/css" />

    <script id="books" type="text/x-jquery-tmpl">
    <div id="bookHolder">Name: ${bookName} <br />
    Author: ${author} <br />
    Genre: ${genre} <br />
    Price: ${price} 
    <form id="form1" runat="server">
    <div id="heading">Books Catalog</div>
    <div id="mainDiv">

With some ugly basic styling, here is what the final page looks like. Please note that there was absolutely no DOM manipulation in the Javascript code. Conventional approaches would have required iterating through the xml file, creating DOM elements, assigning their node value, taking care of their hierarchy etc. JQuery’s templating plugin rids us of most of this additional plumbing code and makes the script files more concise and readable.