Click here to Skip to main content
Click here to Skip to main content

Client Templating with jQuery

, 15 Nov 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
This article discusses a very cool feature of jQuery that is Client Templating

Table of Contents

Introduction

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.

What is jQuery

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.

Prerequisites

  • 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. Smile | :)

To download JSON library, click here.

jQuery Templating

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:

Client Templating

Figure: How Client Templating works

Templates

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.

//It gets called as soon as DOM gets loaded 

 $(document).ready(function() {
           PopulatePersons();
       });

 //Creating the ajax call, and if succeeded then display the result on UI
 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

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 addresses. It means an employeee can belong to multiple addresses. 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 Addresses and applies the templating on the template AddressTemplate.

Please find the entire code in the attached sample.

Now let's run the application:

Nested Templates

Figure: Nested Templates in Action

Microsoft Announcements

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.

Conclusion

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.

Feedback and Suggestions

Hope you like this article. Please give your valuable feedback which will be very helpful for me to write better content next time.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Brij
Software Developer (Senior)
India India
Brij is a 3-times Microsoft MVP in ASP.NET/IIS Category and a passionate .NET developer. More than 6 years of experience in IT field, currently serving a MNC as a Tech Lead/Architect.
 
He is a very passionate .NET developer and have expertise over Web technologies like ASP.NET 2.0/3.5/4.0, jQuery, JSON, Javascript, IIS and related technologies. He is also a Exchange Server (EWS) Specialist. He has great experience in design patterns and N-Tier Architecture.
 
He is also certified as Microsoft Certified Technologies Specialist-ASP.NET and Microsoft Certified Technologies Specialist-WCF in .NET 4.0. He has also received several awards at various forums and his various articles got listed as "Article of the day" at ASP.NET Microsoft Official Website www.asp.net.
 
He has done MCA from NIT Durgapur and completed his graduation from Lucknow University.
 
Learning new technologies and sharing knowledge excites him most. Blogging, solving problems at various forums, helping people, keeps him busy entire day.


Visit his Blog: Brij's arena of .NET
 
Area of Expertise :
C#, ASP.NET 2.0,3.5,4.0, AJAX, JQuery, JSON, XML, XSLT, ADO.Net, WCF, Active Directory, Exchange Server 2007 (EWS), Java script, Web Services ,Win services, DotnetNuke, WSS 3.0,Sharepoint Designer, SQL Server 2000/2005/2008
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 2 PinmemberMember 987791011-Sep-13 22:39 
QuestionMy vote of 5 PinmemberJaime García30-Aug-13 3:11 
GeneralMy vote of 5 PinmemberAdebayo James12-Jul-13 1:32 
GeneralMy vote of 5 PinmemberForogar22-Feb-13 4:47 
GeneralMy vote of 5 PinmemberSavalia Manoj M8-Nov-12 17:33 
GeneralMy vote of 5 PinmemberKalpesh Desai25-Mar-12 10:36 
GeneralMy vote of 5 Pinmembermanoj kumar choubey2-Feb-12 23:55 
QuestionMy Five... PinmemberPaul Conrad7-Aug-11 9:28 
AnswerRe: My Five... PinmvpBrij7-Aug-11 9:30 
GeneralMy vote of 5 PinmemberMember 34159525-Apr-11 20:26 
GeneralRe: My vote of 5 PinmvpBrij25-Apr-11 20:47 
GeneralMy vote of 3 PinmembermasterJalchr11-Jan-11 4:45 
GeneralRe: My vote of 3 PinmvpBrij11-Jan-11 7:29 
GeneralRe: My vote of 3 Pinmvpthatraja26-Feb-11 18:56 
masterJalchr wrote:
There are no tricks for the professionals ... simply a starter's article.

Actually He Tagged the article as Beginner/Intermediate which means the article mainly for starters.
BTW you may re-vote him. Cheers. Smile | :)
thatraja

My Tip/Tricks
My Dad had a Heart Attack on this day so don't...

GeneralRe: My vote of 3 PinmembermasterJalchr28-Feb-11 0:06 
GeneralRe: My vote of 3 Pinmvpthatraja28-Feb-11 0:09 
GeneralMy vote of 4 PinmemberSchmuli11-Jan-11 0:53 
GeneralRe: My vote of 4 PinmvpBrij11-Jan-11 7:31 
GeneralRe: My vote of 4 PinmemberAdam Tibi27-Jan-11 0:16 
GeneralRe: My vote of 4 PinmemberSchmuli2-Feb-11 5:52 
QuestionPermissions Client Side ? PinmemberMember 382109310-Jan-11 6:02 
AnswerRe: Permissions Client Side ? PinmvpBrij11-Jan-11 20:44 
GeneralWell deserved PinmemberMarcelo Ricardo de Oliveira2-Jan-11 6:26 
GeneralRe: Well deserved PinmvpBrij9-Jan-11 7:19 
GeneralRe: Well deserved PinmvpMarcelo Ricardo de Oliveira9-Jan-11 7:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.141216.1 | Last Updated 15 Nov 2010
Article Copyright 2010 by Brij
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid