A quick introduction of using jTemplate against AJAX JSON data


jQuery has a few template plugins, the most widely accepted is jTemplate. jTemplate is a JQuery template engine that works with AJAX and JSON data. We can use jTemplate in the following steps:

First, download the JQuery JavaScript file and reference it in your web page:

  1. <scrip src="scripts/jQuery-jtemplates.min.js" type="text/javascript"></script>

<scrip src="scripts/jQuery-jtemplates.min.js" type="text/javascript"></script>

Second, define your template:


  1. <script type="text/html" id="TemplateResultsTable">  
  2. {#template MAIN}  
  3. <table  cellpadding="10" cellspacing="0">  
  4.   <tr>  
  5.     <th>Artist</th>  
  6.     <th>Company</th>  
  7.     <th>Title</th>  
  8.     <th>Price</th>  
  9.   </tr>  
  10.   {#foreach $T.d as CD}  
  11.     {#include ROW root=$T.CD}  
  12.   {#/for}  
  13. </table>  
  14. {#/template MAIN}  
  15. {#template ROW}  
  16. <tr class="{#cycle values=[”,’evenRow’]}">  
  17.   <td>{$T.Artist}</td>  
  18.   <td>{$T.Company}</td>  
  19.   <td>{$T.Title}</td>  
  20.   <td>{$T.Price}</td>  
  21. </tr>  
  22. {#/template ROW}  
  23. </script> 

Please note that we define the template in a script block, which can be accessed by its id; also, $T is a reference to the data item passed to the template.

Third, call your web service in your script, designate the template and instantiate it with data.

  1. $(document).ready(function() {  
  2.           $.ajax({  
  3.               type: "POST",  
  4.               url: "CDCatalog.asmx/GetCDCatalog",  
  5.               data: "{}",  
  6.               contentType: "application/json; charset=utf-8",  
  7.               dataType: "json",  
  8.               success: function(msg) {  
  9. //instantiate a template with data
  10.                   ApplyTemplate(msg);   
  11.               }  
  12.           });  
  13.       });  
  14. function ApplyTemplate(msg) {  
  15.       $(‘#Container’).setTemplate($("#TemplateResultsTable").html());  
  16.       $(‘#Container’).processTemplate(msg);  
  17. }

For more info please visit Xun Ding’s excellent article Using jQuery with ASP .NET


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s