To implement the jQuery templating plugin, you need to include the jQuery scripts as shown below:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="jquery.tmpl.js"></script>
Note that both jQuery 1.4.4 and jQuery Templates can be downloaded from Microsoft Ajax Content Delivery Network. Also, notice the usage of the script
tag with a special MIME type.
The next step is creating a template using jQuery. Here is an example:
<script id="employeeTemplate" type="text/x-jQuery-tmpl">
<div>
<img src="EmployeePictures/${picture}" alt="" />
<h2>${Name}</h2>
</div>
</script>
Next, create some data to render. Here is an example:
var employees = [
{ Name: "Peter Sanders", "E001" },
{ Name: "Joydip Kanjilal", "E002" },
{ Name: "Steve Mitch", "E003" },
{ Name: "Peter Dan", "E004" },
{ Name: "Jim Kanjilal", "E005" },
];
The Complete jQuery Template Source Code
The following plugin script illustrates how you can display a list of employees stored in a JavaScript array:
<body>
<div id="pageContent">
<h1>Employee Records</h1>
<div id="employeeContainer"></div>
</div>
<script id="employeeTemplate" type="text/x-jQuery-tmpl">
<div>
<img src="EmployeePictures/${picture}" alt="" />
<h2>${Name}</h2>
</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">
var employees = [
{ Name: "Peter Sanders", "E001" },
{ Name: "Joydip Kanjilal", "E002" },
{ Name: "Steve Mitch", "E003" },
{ Name: "Peter Dan", "E004" },
]; $("#employeeTemplate").tmpl(books).appendTo("#employeeContainer");
</script>
</body>
Defining a jQuery Template Externally
You can also define a template externally and use it in your markup code. To do this, you should define a template in a data file. For example, you could create the following data file and name it EmployeeTemplate.htm:
<p>Hello, ${empname}.</p>
Then you can define the employee object as shown below:
var employees = { empname: 'Joydip' };
You could then load the external template stored in the external file (EmployeeTemplate.htm) using the $.get()
method and then render the external template using jQuery templates. Here is how to do that:
$.get('EmployeeTemplate.htm', function(template) {
$.tmpl(template, employee).appendTo('body');
});
Summary
JQuery is a simple, light-weight and fast JavaScript library that has simplified the way you write your scripts. In this article we discussed the features of jQuery and how we can work with the jQuery templates. We also discussed how we can create and use jQuery templates in your application.
References
jQuery Templates intro by Stephen Walther
jQuery Templates Plugin Documentation
jQuery Templates and Data Linking blog by Scott Guthrie