jQuery Template

While writing applications whenever data is fetched with post request from the server/database, in return we create DOM elements to represent that data. Now here we do all the messy code to put the string together in the javascript code and iterate the result set to display the data.

At that time it would be great indeed help if we have some kind of template engine, which could display/render data without parsing and doing lot of messy code.

Lets c in action and answer our HOW can we implement jQuery-template.
  1. <html>  
  2. <head>  
  3.     <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.js"></script>  
  4.     <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>  
  5. </head>  
  6. <body>  
  7.         <div id="pageContent">  
  8.              <h1><center>Indian Players</center></h1>  
  9.              <div id="container"></div>  
  10.         </div>  
  11.           
  12.         <script id="players" type="text/x-jQuery-tmpl">  
  13.             <div>  
  14.                 <h2>${name}</h2>   
  15.                 <img src="${picture}" alt="" style="border:2px solid blue"/>  
  16.                 Matches: ${matches}  
  17.             </div>  
  18.         </script>  
  19.           
  20.         <script>  
  21.             var cricketers = [  
  22.                    { name: "Sachin Tendulkar", matches: 434, picture: "sachin.jpg" },  
  23.                    { name: "Virendra Sehwag", matches: 334, picture: "sehwag.jpg" },  
  24.                    { name: "Rahul Dravid", matches: 384, picture: "dravid.jpg" },  
  25.                    { name: "Dhoni", matches: 280, picture: "dhoni.jpg" },  
  26.                ];  
  27.            $("#players").tmpl(cricketers).appendTo("#container");  
  28.         </script>  
  29. </body>  
  30. </html>