An Introduction to jQuery Templates

Posted by Stephen Walther on Stephen Walter See other posts from Stephen Walter or by Stephen Walther
Published on Wed, 01 Dec 2010 02:00:43 GMT Indexed on 2010/12/06 16:59 UTC
Read the original article Hit count: 6136

Filed under:
|
|

The goal of this blog entry is to provide you with enough information to start working with jQuery Templates. jQuery Templates enable you to display and manipulate data in the browser. For example, you can use jQuery Templates to format and display a set of database records that you have retrieved with an Ajax call.

jQuery Templates supports a number of powerful features such as template tags, template composition, and wrapped templates. I’ll concentrate on the features that I think that you will find most useful.

In order to focus on the jQuery Templates feature itself, this blog entry is server technology agnostic. All the samples use HTML pages instead of ASP.NET pages. In a future blog entry, I’ll focus on using jQuery Templates with ASP.NET Web Forms and ASP.NET MVC (You can do some pretty powerful things when jQuery Templates are used on the client and ASP.NET is used on the server).

Introduction to jQuery Templates

The jQuery Templates plugin was developed by the Microsoft ASP.NET team in collaboration with the open-source jQuery team. While working at Microsoft, I wrote the original proposal for jQuery Templates, Dave Reed wrote the original code, and Boris Moore wrote the final code. The jQuery team – especially John Resig – was very involved in each step of the process. Both the jQuery community and ASP.NET communities were very active in providing feedback.

jQuery Templates will be included in the jQuery core library (the jQuery.js library) when jQuery 1.5 is released. Until jQuery 1.5 is released, you can download the jQuery Templates plugin from the jQuery Source Code Repository or you can use jQuery Templates directly from the ASP.NET CDN.

The documentation for jQuery Templates is already included with the official jQuery documentation at http://api.jQuery.com. The main entry for jQuery templates is located under the topic plugins/templates.

A Basic Sample of jQuery Templates

Let’s start with a really simple sample of using jQuery Templates. We’ll use the plugin to display a list of books stored in a JavaScript array. Here’s the complete code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head>
    <title>Intro</title>
    <link href="0_Site.css" rel="stylesheet" type="text/css" />
</head>
<body>

    <div id="pageContent">
    
        <h1>ASP.NET Bookstore</h1>

        <div id="bookContainer"></div>
    
    </div>

    <script id="bookTemplate" type="text/x-jQuery-tmpl">
        <div>
            <img src="BookPictures/${picture}" alt="" />
            <h2>${title}</h2>
            price: ${formatPrice(price)}
        </div>
    </script>

    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>

    <script type="text/javascript">
        // Create an array of books
        var books = [
            { title: "ASP.NET 4 Unleashed", price: 37.79, picture: "AspNet4Unleashed.jpg" },
            { title: "ASP.NET MVC Unleashed", price: 44.99, picture: "AspNetMvcUnleashed.jpg" },
            { title: "ASP.NET Kick Start", price: 4.00, picture: "AspNetKickStart.jpg" },
            { title: "ASP.NET MVC Unleashed iPhone", price: 44.99, picture: "AspNetMvcUnleashedIPhone.jpg" },
        ];

        // Render the books using the template
        $("#bookTemplate").tmpl(books).appendTo("#bookContainer");


        function formatPrice(price) {
            return "$" + price.toFixed(2);
        }

    </script>

</body>
</html>

When you open this page in a browser, a list of books is displayed:

clip_image002

There are several things going on in this page which require explanation.

First, notice that the page uses both the jQuery 1.4.4 and jQuery Templates libraries. Both libraries are retrieved from the ASP.NET CDN:

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script>

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>

You can use the ASP.NET CDN for free (even for production websites). You can learn more about the files included on the ASP.NET CDN by visiting the ASP.NET CDN documentation page.

Second, you should notice that the actual template is included in a script tag with a special MIME type:

<script id="bookTemplate" type="text/x-jQuery-tmpl">
    <div>
        <img src="BookPictures/${picture}" alt="" />
        <h2>${title}</h2>
        price: ${formatPrice(price)}
    </div>
</script>

This template is displayed for each of the books rendered by the template. The template displays a book picture, title, and price.

Notice that the SCRIPT tag which wraps the template has a MIME type of text/x-jQuery-tmpl. Why is the template wrapped in a SCRIPT tag and why the strange MIME type?

When a browser encounters a SCRIPT tag with an unknown MIME type, it ignores the content of the tag. This is the behavior that you want with a template. You don’t want a browser to attempt to parse the contents of a template because this might cause side effects.

For example, the template above includes an <img> tag with a src attribute that points at “BookPictures/${picture}”. You don’t want the browser to attempt to load an image at the URL “BookPictures/${picture}”. Instead, you want to prevent the browser from processing the IMG tag until the ${picture} expression is replaced by with the actual name of an image by the jQuery Templates plugin.

If you are not worried about browser side-effects then you can wrap a template inside any HTML tag that you please. For example, the following DIV tag would also work with the jQuery Templates plugin:

<div id="bookTemplate" style="display:none">
    <div>
        <h2>${title}</h2>
        price: ${formatPrice(price)}
    </div>
</div>

Notice that the DIV tag includes a style=”display:none” attribute to prevent the template from being displayed until the template is parsed by the jQuery Templates plugin.

Third, notice that the expression ${…} is used to display the value of a JavaScript expression within a template. For example, the expression ${title} is used to display the value of the book title property. You can use any JavaScript function that you please within the ${…} expression. For example, in the template above, the book price is formatted with the help of the custom JavaScript formatPrice() function which is defined lower in the page.

Fourth, and finally, the template is rendered with the help of the tmpl() method. The following statement selects the bookTemplate and renders an array of books using the bookTemplate. The results are appended to a DIV element named bookContainer by using the standard jQuery appendTo() method.

$("#bookTemplate").tmpl(books).appendTo("#bookContainer");

Using Template Tags

Within a template, you can use any of the following template tags.

  • {{tmpl}} – Used for template composition. See the section below.
  • {{wrap}} – Used for wrapped templates. See the section below.
  • {{each}} – Used to iterate through a collection.
  • {{if}} – Used to conditionally display template content.
  • {{else}} – Used with {{if}} to conditionally display template content.
  • {{html}} – Used to display the value of an HTML expression without encoding the value. Using ${…} or {{= }} performs HTML encoding automatically.
  • {{= }}-- Used in exactly the same way as ${…}.
  • {{! }} – Used for displaying comments. The contents of a {{!...}} tag are ignored.

For example, imagine that you want to display a list of blog entries. Each blog entry could, possibly, have an associated list of categories. The following page illustrates how you can use the { if}} and {{each}} template tags to conditionally display categories for each blog entry:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>each</title>
    <link href="1_Site.css" rel="stylesheet" type="text/css" />
</head>
<body>

    <div id="blogPostContainer"></div>


    <script id="blogPostTemplate" type="text/x-jQuery-tmpl">
    
    <h1>${postTitle}</h1>
    <p>
        ${postEntry}
    </p>
    
    {{if categories}}  
      Categories: {{each categories}} <i>${$value}</i> {{/each}}
    {{else}}
      Uncategorized
    {{/if}}

    </script>

    
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>

    <script type="text/javascript">

            var blogPosts = [
                {
                    postTitle: "How to fix a sink plunger in 5 minutes",
                    postEntry: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.",
                    categories: ["HowTo", "Sinks", "Plumbing"]
                },
                {
                    postTitle: "How to remove a broken lightbulb",
                    postEntry: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.",
                    categories: ["HowTo", "Lightbulbs", "Electricity"]
                },
                {
                    postTitle: "New associate website",
                    postEntry: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna."
                }
            ];


            // Render the blog posts
            $("#blogPostTemplate").tmpl(blogPosts).appendTo("#blogPostContainer");
    
    </script>


</body>
</html>

When this page is opened in a web browser, the following list of blog posts and categories is displayed:

clip_image003

Notice that the first and second blog entries have associated categories but the third blog entry does not. The third blog entry is “Uncategorized”.

The template used to render the blog entries and categories looks like this:

<script id="blogPostTemplate" type="text/x-jQuery-tmpl">
    
    <h1>${postTitle}</h1>
    <p>
        ${postEntry}
    </p>
    
    {{if categories}}  
      Categories: {{each categories}} <i>${$value}</i> {{/each}}
    {{else}}
      Uncategorized
    {{/if}}

</script>

Notice the special expression $value used within the {{each}} template tag. You can use $value to display the value of the current template item. In this case, $value is used to display the value of each category in the collection of categories.

Template Composition

When building a fancy page, you might want to build a template out of multiple templates. In other words, you might want to take advantage of template composition.

For example, imagine that you want to display a list of products. Some of the products are being sold at their normal price and some of the products are on sale. In that case, you might want to use two different templates for displaying a product: a productTemplate and a productOnSaleTemplate.

clip_image004

The following page illustrates how you can use the {{tmpl}} tag to build a template from multiple templates:

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Composition</title>
    <link href="2_Site.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <div id="pageContainer">

        <h1>Products</h1>
        <div id="productListContainer"></div>

        <!-- Show list of products using composition -->
        <script id="productListTemplate" type="text/x-jQuery-tmpl">
          <div>
            {{if onSale}}
                {{tmpl "#productOnSaleTemplate"}}
            {{else}}
                {{tmpl "#productTemplate"}}
            {{/if}}
          </div>              
        </script>

        <!-- Show product -->
        <script id="productTemplate" type="text/x-jQuery-tmpl">
            ${name} 
        </script>

        <!-- Show product on sale -->
        <script id="productOnSaleTemplate" type="text/x-jQuery-tmpl">
            <b>${name}</b> <img src="images/on_sale.png" alt="On Sale" />
        </script>

    
        <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script>
        <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
        <script type="text/javascript">
            var products = [
                { name: "Laptop", onSale: false },
                { name: "Apples", onSale: true },
                { name: "Comb", onSale: false }
            ];

            $("#productListTemplate").tmpl(products).appendTo("#productListContainer");

        </script>

    </div>
</body>
</html>

 

In the page above, the main template used to display the list of products looks like this:

<script id="productListTemplate" type="text/x-jQuery-tmpl">
  <div>
    {{if onSale}}
        {{tmpl "#productOnSaleTemplate"}}
    {{else}}
        {{tmpl "#productTemplate"}}
    {{/if}}
  </div>              
</script>

 

If a product is on sale then the product is displayed with the productOnSaleTemplate (which includes an on sale image):

<script id="productOnSaleTemplate" type="text/x-jQuery-tmpl">
    <b>${name}</b> <img src="images/on_sale.png" alt="On Sale" />
</script>

 

Otherwise, the product is displayed with the normal productTemplate (which does not include the on sale image):

<script id="productTemplate" type="text/x-jQuery-tmpl">
    ${name} 
</script>

 

You can pass a parameter to the {{tmpl}} tag. The parameter becomes the data passed to the template rendered by the {{tmpl}} tag.

For example, in the previous section, we used the {{each}} template tag to display a list of categories for each blog entry like this:

<script id="blogPostTemplate" type="text/x-jQuery-tmpl">
    
    <h1>${postTitle}</h1>
    <p>
        ${postEntry}
    </p>
    
    {{if categories}}  
      Categories: {{each categories}} <i>${$value}</i> {{/each}}
    {{else}}
      Uncategorized
    {{/if}}

</script>

 

Another way to create this template is to use template composition like this:

<script id="blogPostTemplate" type="text/x-jQuery-tmpl">
    
    <h1>${postTitle}</h1>
    <p>
        ${postEntry}
    </p>
    
    {{if categories}}  
      Categories: {{tmpl(categories) "#categoryTemplate"}}
    {{else}}
      Uncategorized
    {{/if}}

 </script>


 <script id="categoryTemplate" type="text/x-jQuery-tmpl">
    <i>${$data}</i>  &nbsp;  
 </script>

 

Using the {{each}} tag or {{tmpl}} tag is largely a matter of personal preference.

Wrapped Templates

The {{wrap}} template tag enables you to take a chunk of HTML and transform the HTML into another chunk of HTML (think easy XSLT). When you use the {{wrap}} tag, you work with two templates. The first template contains the HTML being transformed and the second template includes the filter expressions for transforming the HTML.

For example, you can use the {{wrap}} template tag to transform a chunk of HTML into an interactive tab strip:

clip_image005

When you click any of the tabs, you see the corresponding content.

This tab strip was created with the following page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Wrapped Templates</title>
    
    <style type="text/css">
        body {
            font-family: Arial;
            background-color:black;
        }

        .tabs div {
            display:inline-block;
            border-bottom: 1px solid black;
            padding:4px;
            background-color:gray;   
            cursor:pointer;
        }
        
        .tabs div.tabState_true {
            background-color:white;
            border-bottom:1px solid white;   
        }

        .tabBody {
            border-top:1px solid white;
            padding:10px;
            background-color:white;
            min-height:400px;
            width:400px;
        }

    </style>

</head>
<body>
    <div id="tabsView"></div>


    <script id="tabsContent" type="text/x-jquery-tmpl">
    {{wrap "#tabsWrap"}}
        <h3>Tab 1</h3>
        <div>
            Content of tab 1.
            Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.
        </div>

        <h3>Tab 2</h3>
        <div>
            Content of tab 2.
            Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.   
        </div>

        <h3>Tab 3</h3>
        <div>
            Content of tab 3. 
            Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.
        </div>
    {{/wrap}}
    </script>


    <script id="tabsWrap" type="text/x-jquery-tmpl">
        <div class="tabs">
            {{each $item.html("h3", true)}}
                <div class="tabState_${$index === selectedTabIndex}">
                    ${$value}
                </div>
            {{/each}}
        </div>
        <div class="tabBody">
            {{html $item.html("div")[selectedTabIndex]}}
        </div>
    </script>


    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>

    <script type="text/javascript">
        // Global for tracking selected tab
        var selectedTabIndex = 0;

        // Render the tab strip
        $("#tabsContent").tmpl().appendTo("#tabsView");

        // When a tab is clicked, update the tab strip
        $("#tabsView")
            .delegate(".tabState_false", "click", function () {
                var templateItem = $.tmplItem(this);
                selectedTabIndex = $(this).index();
                templateItem.update();
            });

    </script>

</body>
</html>

 

The “source” for the tab strip is contained in the following template:

<script id="tabsContent" type="text/x-jquery-tmpl">
{{wrap "#tabsWrap"}}
    <h3>Tab 1</h3>
    <div>
        Content of tab 1.
        Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.
    </div>

    <h3>Tab 2</h3>
    <div>
        Content of tab 2.
        Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.   
    </div>

    <h3>Tab 3</h3>
    <div>
        Content of tab 3. 
        Lorem ipsum dolor <b>sit</b> amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.
    </div>
{{/wrap}}
</script>

 

The tab strip is created with a list of H3 elements (which represent each tab) and DIV elements (which represent the body of each tab). Notice that the HTML content is wrapped in the {{wrap}} template tag. This template tag points at the following tabsWrap template:

<script id="tabsWrap" type="text/x-jquery-tmpl">
    <div class="tabs">
        {{each $item.html("h3", true)}}
            <div class="tabState_${$index === selectedTabIndex}">
                ${$value}
            </div>
        {{/each}}
    </div>
    <div class="tabBody">
        {{html $item.html("div")[selectedTabIndex]}}
    </div>
</script>

The tabs DIV contains all of the tabs. The {{each}} template tag is used to loop through each of the H3 elements from the source template and render a DIV tag that represents a particular tab.

The template item html() method is used to filter content from the “source” HTML template. The html() method accepts a jQuery selector for its first parameter. The tabs are retrieved from the source template by using an h3 filter.

The second parameter passed to the html() method – the textOnly parameter -- causes the filter to return the inner text of each h3 element. You can learn more about the html() method at the jQuery website (see the section on $item.html()).

The tabBody DIV renders the body of the selected tab. Notice that the {{html}} template tag is used to display the tab body so that HTML content in the body won’t be HTML encoded.

The html() method is used, once again, to grab all of the DIV elements from the source HTML template. The selectedTabIndex global variable is used to display the contents of the selected tab.

Remote Templates

A common feature request for jQuery templates is support for remote templates. Developers want to be able to separate templates into different files.

Adding support for remote templates requires only a few lines of extra code (Dave Ward has a nice blog entry on this). For example, the following page uses a remote template from a file named BookTemplate.htm:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Remote Templates</title>
    <link href="0_Site.css" rel="stylesheet" type="text/css" />
</head>
<body>

    <div id="pageContent">
    
        <h1>ASP.NET Bookstore</h1>

        <div id="bookContainer"></div>
    
    </div>


    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>

    <script type="text/javascript">
        // Create an array of books
        var books = [
            { title: "ASP.NET 4 Unleashed", price: 37.79, picture: "AspNet4Unleashed.jpg" },
            { title: "ASP.NET MVC Unleashed", price: 44.99, picture: "AspNetMvcUnleashed.jpg" },
            { title: "ASP.NET Kick Start", price: 4.00, picture: "AspNetKickStart.jpg" },
            { title: "ASP.NET MVC Unleashed iPhone", price: 44.99, picture: "AspNetMvcUnleashedIPhone.jpg" },
        ];

        // Get the remote template
        $.get("BookTemplate.htm", null, function (bookTemplate) {

            // Render the books using the remote template
            $.tmpl(bookTemplate, books).appendTo("#bookContainer");            
        });



        function formatPrice(price) {
            return "$" + price.toFixed(2);
        }

    </script>

</body>
</html>

 

The remote template is retrieved (and rendered) with the following code:

// Get the remote template
$.get("BookTemplate.htm", null, function (bookTemplate) {

    // Render the books using the remote template
    $.tmpl(bookTemplate, books).appendTo("#bookContainer");            
});

 

This code uses the standard jQuery $.get() method to get the BookTemplate.htm file from the server with an Ajax request. After the BookTemplate.htm file is successfully retrieved, the $.tmpl() method is used to render an array of books with the template. Here’s what the BookTemplate.htm file looks like:

<div>
    <img src="BookPictures/${picture}" alt="" />
    <h2>${title}</h2>
    price: ${formatPrice(price)}
</div>

Notice that the template in the BooksTemplate.htm file is not wrapped by a SCRIPT element. There is no need to wrap the template in this case because there is no possibility that the template will get interpreted before you want it to be interpreted.

If you plan to use the bookTemplate multiple times – for example, you are paging or sorting the books -- then you should compile the template into a function and cache the compiled template function.

For example, the following page can be used to page through a list of 100 products (using iPhone style More paging).

clip_image006

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Template Caching</title>
    <link href="6_Site.css" rel="stylesheet" type="text/css" />
</head>
<body>

    <h1>Products</h1>

    <div id="productContainer"></div>

    <button id="more">More</button>

    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>

    <script type="text/javascript">
        // Globals
        var pageIndex = 0;
        
        // Create an array of products
        var products = [];
        for (var i = 0; i < 100; i++) {
            products.push({ name: "Product " + (i + 1) });
        }

        // Get the remote template
        $.get("ProductTemplate.htm", null, function (productTemplate) {

            // Compile and cache the template
            $.template("productTemplate", productTemplate);

            // Render the products
            renderProducts(0);
        });

        $("#more").click(function () {
            pageIndex++;
            renderProducts();
        });

        function renderProducts() {
            // Get page of products
            var pageOfProducts = products.slice(pageIndex * 5, pageIndex * 5 + 5);

            // Used cached productTemplate to render products
            $.tmpl("productTemplate", pageOfProducts).appendTo("#productContainer");
        }


        function formatPrice(price) {
            return "$" + price.toFixed(2);
        }

    </script>

</body>
</html>

 

The ProductTemplate is retrieved from an external file named ProductTemplate.htm. This template is retrieved only once. Furthermore, it is compiled and cached with the help of the $.template() method:

// Get the remote template
$.get("ProductTemplate.htm", null, function (productTemplate) {

    // Compile and cache the template
    $.template("productTemplate", productTemplate);

    // Render the products
    renderProducts(0);
});

 

The $.template() method compiles the HTML representation of the template into a JavaScript function and caches the template function with the name productTemplate.

The cached template can be used by calling the $.tmp() method. The productTemplate is used in the renderProducts() method:

function renderProducts() {
    // Get page of products
    var pageOfProducts = products.slice(pageIndex * 5, pageIndex * 5 + 5);

    // Used cached productTemplate to render products
    $.tmpl("productTemplate", pageOfProducts).appendTo("#productContainer");
}

In the code above, the first parameter passed to the $.tmpl() method is the name of a cached template.

Working with Template Items

In this final section, I want to devote some space to discussing Template Items. A new Template Item is created for each rendered instance of a template. For example, if you are displaying a list of 100 products with a template, then 100 Template Items are created.

A Template Item has the following properties and methods:

  • data – The data associated with the Template Instance. For example, a product.
  • tmpl – The template associated with the Template Instance.
  • parent – The parent template item if the template is nested.
  • nodes – The HTML content of the template.
  • calls – Used by {{wrap}} template tag.
  • nest – Used by {{tmpl}} template tag.
  • wrap – Used to imperatively enable wrapped templates.
  • html – Used to filter content from a wrapped template. See the above section on wrapped templates.
  • update – Used to re-render a template item.

The last method – the update() method -- is especially interesting because it enables you to re-render a template item with new data or even a new template.

For example, the following page displays a list of books. When you hover your mouse over any of the books, additional book details are displayed. In the following screenshot, details for ASP.NET Kick Start are displayed.

clip_image008

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Template Item</title>
    <link href="0_Site.css" rel="stylesheet" type="text/css" />
</head>
<body>

    <div id="pageContent">
    
        <h1>ASP.NET Bookstore</h1>

        <div id="bookContainer"></div>
    
    </div>

    <script id="bookTemplate" type="text/x-jQuery-tmpl">
        <div class="bookItem">
            <img src="BookPictures/${picture}" alt="" />
            <h2>${title}</h2>
            price: ${formatPrice(price)}
        </div>
    </script>


    <script id="bookDetailsTemplate" type="text/x-jQuery-tmpl">
        <div class="bookItem">
            <img src="BookPictures/${picture}" alt="" />
            <h2>${title}</h2>
            price: ${formatPrice(price)}
            <p>
                ${description}
            </p>
        </div>
    </script>



    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>

    <script type="text/javascript">
        // Create an array of books
        var books = [
            { title: "ASP.NET 4 Unleashed", price: 37.79, picture: "AspNet4Unleashed.jpg", description: "The most comprehensive book on Microsoft’s new ASP.NET 4.. " },
            { title: "ASP.NET MVC Unleashed", price: 44.99, picture: "AspNetMvcUnleashed.jpg", description: "Writing for professional programmers, Walther explains the crucial concepts that make the Model-View-Controller (MVC) development paradigm work…" },
            { title: "ASP.NET Kick Start", price: 4.00, picture: "AspNetKickStart.jpg", description: "Visual Studio .NET is the premier development environment for creating .NET applications…." },
            { title: "ASP.NET MVC Unleashed iPhone", price: 44.99, picture: "AspNetMvcUnleashedIPhone.jpg", description: "ASP.NET MVC Unleashed for the iPhone…" },
        ];

        // Render the books using the template
        $("#bookTemplate").tmpl(books).appendTo("#bookContainer");

        // Get compiled details template
        var bookDetailsTemplate = $("#bookDetailsTemplate").template();

        // Add hover handler
        $(".bookItem").mouseenter(function () {
            // Get template item associated with DIV
            var templateItem = $(this).tmplItem();

            // Change template to compiled template
            templateItem.tmpl = bookDetailsTemplate;
            
            // Re-render template
            templateItem.update();
        });


        function formatPrice(price) {
            return "$" + price.toFixed(2);
        }

    </script>

</body>
</html>

 

There are two templates used to display a book: bookTemplate and bookDetailsTemplate. When you hover your mouse over a template item, the standard bookTemplate is swapped out for the bookDetailsTemplate. The bookDetailsTemplate displays a book description.

The books are rendered with the bookTemplate with the following line of code:

// Render the books using the template

$("#bookTemplate").tmpl(books).appendTo("#bookContainer");

 

The following code is used to swap the bookTemplate and the bookDetailsTemplate to show details for a book:

// Get compiled details template
var bookDetailsTemplate = $("#bookDetailsTemplate").template();

// Add hover handler
$(".bookItem").mouseenter(function () {
    // Get template item associated with DIV
    var templateItem = $(this).tmplItem();

    // Change template to compiled template
    templateItem.tmpl = bookDetailsTemplate;
    
    // Re-render template
    templateItem.update();
});

 

When you hover your mouse over a DIV element rendered by the bookTemplate, the mouseenter handler executes. First, this handler retrieves the Template Item associated with the DIV element by calling the tmplItem() method. The tmplItem() method returns a Template Item.

Next, a new template is assigned to the Template Item. Notice that a compiled version of the bookDetailsTemplate is assigned to the Template Item’s tmpl property. The template is compiled earlier in the code by calling the template() method.

Finally, the Template Item update() method is called to re-render the Template Item with the bookDetailsTemplate instead of the original bookTemplate.

Summary

This is a long blog entry and I still have not managed to cover all of the features of jQuery Templates J However, I’ve tried to cover the most important features of jQuery Templates such as template composition, template wrapping, and template items.

To learn more about jQuery Templates, I recommend that you look at the documentation for jQuery Templates at the official jQuery website. Another great way to learn more about jQuery Templates is to look at the (unminified) source code.

© Stephen Walter or respective owner

Related posts about AJAX

Related posts about jQuery