Table of Contents
jQuery templating is becoming a new buzzword for the new Web applications. One cannot avoid jQuery in web applications. Currently, most of the applications are using jQuery heavily. It provides a very good look & feel and better performance.
A lot of plugins are also available for jQuery, they provide really cool features. We can provide a very new and trendy look and feel with the help of jQuery. Also, as we are making very rich applications, performance is also becoming a key point for our applications. jQuery helps a lot in this regard also. We will be discussing mainly jQuery Templating in this article.
jQuery is a JavaScript library that works on top of the JavaScript. jQuery provides a very simple way for HTML document traversing, DOM manipulation, event handling, animating, and Ajax interactions for rapid web development. That could have been very complex while working with normal JavaScript.
jQuery is becoming more and more popular day by day. It was even integrated with VS2008 and also available with VS2010. jQuery is open source. Due to its features, Microsoft started to support jQuery team and also working with them, to provide better web based tools to their Clients.
- jQuery library
- A plugin for templating
- JSON library
jQuery already comes with VS2008/2010. But if you are working with VS 2005, then you can download from the following link.
To download plugin for templating feature, click here.
Relax guys!! You won't need this plugin after jQuery 1.5. This would be integrated with the main library itself. :)
To download JSON library, click here.
As we are working on Client server architecture, most of the things are done by the server itself. Server sends the HTML response to the browser and the browser just display it. Earlier, we were not doing a lot of things at the client side, Normally, some validation and a little bit more at client side. With the help of Ajax call from client side and retrieving data in a very convenient format in JSON, it really becomes easy, to start moving server side code to Client side. This means the data travelling from server to client is not the whole HTML response but it is just data that we have to show in different HTML controls.
Let's see an pictorial overview:
Figure: How Client Templating works
To use client templating, you need the following:
- First, data at client side
- Client side template
- Now with the help of jQuery, make the HTML elements and adding it to the DOM.
Now I am explaining one example. A sample is attached with this article.
In my example, I am displaying a list of Persons
and also adding a Person
later.
Displaying Data
So here, first I am showing the details of Persons
. The data is coming in JSON format with the help of Ajax call, in document.ready
function.
Let's move step by step:
I have created a Client template to display the person
data.The template is:
<script type="text/html" id="personTemplate">
<div>
<div style="float:left;"> ID : </div> <div>${UId} </div>
<div style="float:left;"> Name : </div> <div>${Name} </div>
<div style="float:left;"> Address : </div> <div>${Address} </div> <br />
</div>
</script>
But, why have I put it in script
tag? Because we don't want to render it. We will be using this as a template for displaying the data. Also see, I have made the type
as text/html
.
Here, in the template, ${UId}, ${Name}
and ${Address}
are replaced by the actual values from the data provided. The name of the properties in the provided class is the same.
At the server side, I made a WebMethod
that will be called from the client to fetch all the person data.
My Person
class is as:
public class Person
{
public int UId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
My WebMethod
is as:
[WebMethod()]
public static string GetPersons()
{
List<person> persons = new List<person>()
{
new Person { UId = 1, Name = "Brij", Address = "Noida"},
new Person { UId = 2, Name = "Rahul", Address = "New Delhi" },
new Person { UId = 3, Name = "John0", Address = "Chris"}
};
JavaScriptSerializer ser = new JavaScriptSerializer();
return ser.Serialize(persons);
}
I created the static
data in the code, one can fetch from where s/he wants, either some database or some file or some other datasource.
Here I have used the namespace System.Web.Script.Serialization
for JavaScript serialization.
I have made an Ajax call at document.ready
to get all the persons
data, and displayed the data on UI.
$(document).ready(function() {
PopulatePersons();
});
function PopulatePersons() {
$.ajax({
type: "POST",
url: "Default.aspx/GetPersons",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
}
function AjaxSucceeded(result) {
Display(result);
}
function AjaxFailed(result) {
alert('no success');
}
After fetching the data, from the server, we are rendering the data using jquery templating feature:
function Display(result) {
var persons = eval(result.d);
personCount = persons.length;
$("#personTemplate").tmpl(persons).appendTo($("#divPerson"));
}
Here, what I am doing is that I am parsing the data that is returned by webservice. After that, I am passing it to the tmpl
function. This line of code...
$("#personTemplate").tmpl(persons).appendTo($("#divPerson"));
...means use the template personTemplate
for rendering the persons
data and add it to the container div
divPerson
.
Adding/Updating Data
For adding more person
on UI, I have added an HTML button on my page, to add a person
. As:
<input id="Button1" type="button" value="AddMorePerson"
onclick="AddPerson();"/>
OnClientclick of Add button, I am fetching the data from server using Ajax call.
function AddPerson() {
var inputs = new Object();
inputs.count = personCount;
$.ajax({
type: "POST",
url: "Template.aspx/AddPerson",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(inputs),
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
}
After fetching the data, display it with the help of client templating as:
function DisplayChildren(result) {
var persons = eval(result.d);
personCount = persons.length;
$("#personTemplate").tmpl(persons).appendTo($("#divPerson"));
}
It just appends the person
detail in the existing div
as above.
Note: One should keep in sync the name of the properties of the class and used in template one.
Nested Templates also work the same as above, but here we'll be using one template in the other. This type of requirement is very common, when we need to show the details of any item one to many or many to many mapping.
So here, I have discussed it with a sample example. Here, I have an employee
class which has a list of address
es. It means an employeee
can belong to multiple address
es. My employee
and address
class are like:
public class Address
{
public string Street { get; set; }
public String AddressLine1 { get; set; }
public String AddressLine2 { get; set; }
public string City { get; set; }
public string Zip { get; set; }
}
and Employee
class:
public class Employee
{
public int EmployeeId { get; set; }
public String Name { get; set; }
public int Age { get; set; }
public List Addresses { get; set; }
<address>}
</address>
Now the webmethod
that is returning the data:
[WebMethod()]
public static string GetEmployees()
{
List<employee> persons = new List<employee>()
{
new Employee { EmployeeId = 1000, Age=34, Name ="Rahul",
Addresses = new List()},
new Employee { EmployeeId = 1001, Age=29, Name ="Atul",
Addresses = new List()},
new Employee { EmployeeId = 1002, Age=32, Name ="Rohan",
Addresses = new List()}
};
persons[0].Addresses.Add(new Address() {
Street = "Street 5", AddressLine1 = "New Bay Area",
AddressLine2 = "Near Roma Hospital", City = "Kolkata", Zip = "221001" });
persons[0].Addresses.Add(new Address() {
Street = "Bahadur marg", AddressLine1 = "Kailash Colony",
AddressLine2 = "Near Public School", City = "Lucknow", Zip = "226001" });
persons[0].Addresses.Add(new Address() {
Street = "Ali Crossing", AddressLine1 = "Republic Colony",
AddressLine2 = "Silk Garden", City = "Ahamedabad", Zip = "221021" });
persons[1].Addresses.Add(new Address() {
Street = "Street No 2", AddressLine1 = "Pocket Gama",
AddressLine2 = "Near Appollo Hospital", City = "G Noida", Zip = "201301" });
persons[1].Addresses.Add(new Address() {
Street = "1634", AddressLine1 = "Sector 15",
AddressLine2 = "Near Nirulas", City = "Noida", Zip = "201301" });
persons[2].Addresses.Add(new Address() {
Street = "Street 10", AddressLine1 = "Sector 18",
AddressLine2 = "Near Mosaic", City = "Noida", Zip = "201301" });
persons[2].Addresses.Add(new Address() {
Street = "Gol Marg", AddressLine1 = "New Era Colony",
AddressLine2 = "Pitambaram", City = "Alllahabad", Zip = "221001" });
JavaScriptSerializer ser = new JavaScriptSerializer();
return ser.Serialize(persons);
}
}
Now as above at the client side, this data is displayed using templating feature.
Now at client side, my client side templates would be:
Parent Template
<script type="text/html" id="empTemplate">
<div>
<div style="float:left;font-weight:bold;"> ID : </div>
<div>${EmployeeId} </div>
<div style="float:left;font-weight:bold;"> Name : </div>
<div>${Name} </div>
<div style="float:left;font-weight:bold;"> Age : </div>
<div>${Age} </div>
<div style="font-weight:bold;">Addresses:</div>
<div style="margin-left:10px;">{{tmpl($data) "#AddressTemplate"}}</div>
</div>
</script>
Child Template
<script id="AddressTemplate" type="text/html">
{{each Addresses}}
<div style="float:left;font-weight:bold;"> Street : </div>
<div>${Street} </div>
<div style="float:left;font-weight:bold;"> AddressLine1 : </div>
<div>${AddressLine1} </div>
<div style="float:left;font-weight:bold;"> AddressLine2 : </div>
<div>${AddressLine2} </div>
<div style="float:left;font-weight:bold;"> City : </div>
<div>${City} </div>
<div style="float:left;font-weight:bold;"> Zip : </div>
<div>${Zip} </div><br />
{{/each}}
</script>
As here you can see in the child template, I have put the template in the tags {{each Addresses}}{{/each}}
. It just renders the inside template for every address. It works like foreach
.
Now inside the parent template, the line code...
{{tmpl($data) "#AddressTemplate"}}
... indicates it gets the data, i.e., here list of Address
es and applies the templating on the template AddressTemplate
.
Please find the entire code in the attached sample.
Now let's run the application:
Figure: Nested Templates in Action
Around a month ago, Microsoft announced three plugins as the new official plugins for jQuery:
- Templating
- Datalinking
- Globalisation
New Official jQuery Plugins Provide Templating, Data Linking and Globalization
In the upcoming version of jQuery (jQuery 1.5) , we would not require to add a plugin for Templating fetaure. This will be part of jQuery 1.5.
In this article, I discussed Templating
and in my upcoming articles, I will be talking about Datalinking
and Globalization
.
As I already discussed in the Introduction section, that jQuery templating provides us a very rich feature to generate the UI without writing much code and in an efficient manner. So one should use templating feature wherever possible. This feature may be very good, where we display a lot of data and also it may get updated. I used it in my application, in almost every page and found it more efficient than server side code.
Hope you like this article. Please give your valuable feedback which will be very helpful for me to write better content next time.