Client Templating with jQuery

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 very good look & feel and better performance.

There are a lot of plugins are also available for jQuery, they provides really cool feature. We can provide a very new and trendy look and feel with the help of jQuery. Also, as we are making very rich application, 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. Even it was 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.

Prerequisite:

  • jQuery library
  • A plugin for templating
  • JSON library

jQuery already comes with VS2008/2010. But if you are working VS 2005 then you can download from the following link.

Download jQuery

To download plugin for templating feature, click here
Relax guys!! you won’t need this plugin after jQuery 1.5. This would 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 browser just display it. Earlier, we were not doing lot of things at client side, Normally, some validation and 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. 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.

Lets see an pictorial overview

jQuery and Ajax

Templates :

To use the 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. In my example, I am displaying 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.Lets move step by step:I have created a Client template to display the person data.The template is:
<br />
 <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>

       </div>

   </script></p>
<p>

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 provided class is same.

At server side, I made a WebMethod that will be called from the
client to fetch all the person data. As

My Person class is as

<br />
public class Person<br />
{<br />
    public int UId { get; set; }<br />
    public string Name { get; set; }<br />
    public string Address { get; set; }<br />
}<br />

My WebMethod is as

<br />
[WebMethod()]<br />
public static string GetPersons()<br />
{<br />
    List persons = new List()<br />
    {<br />
        new Person { UId = 1, Name = "Brij", Address = "Noida"},<br />
        new Person { UId = 2, Name = "Rahul", Address = "New Delhi" },<br />
        new Person { UId = 3, Name = "John0", Address = "Chris"}<br />
    };</p>
<p>    JavaScriptSerializer ser = new JavaScriptSerializer();<br />
    return ser.Serialize(persons);</p>
<p>}<br />

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 a 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

<br />
 $(document).ready(function() {<br />
           PopulatePersons();<br />
       });</p>
<p> //Creating the ajax call, and if succeeded then display the result on UI<br />
 function PopulatePersons() {<br />
     $.ajax({<br />
         type: "POST",<br />
         url: "Default.aspx/GetPersons",<br />
         contentType: "application/json; charset=utf-8",<br />
         data: "{}",<br />
         dataType: "json",<br />
         success: AjaxSucceeded,<br />
         error: AjaxFailed<br />
     });</p>
<p>        }<br />
        function AjaxSucceeded(result) {<br />
            Display(result);<br />
        }<br />
        function AjaxFailed(result) {<br />
            alert('no success');<br />
        }</p>
<p>

After fetching the data, from the server, we are rendering the data using jquery
templatng feature

<br />
function Display(result) {</p>
<p>            var persons = eval(result.d);<br />
            personCount = persons.length;<br />
                $("#personTemplate").tmpl(persons).appendTo($("#divPerson"));<br />
        }<br />

Here , what I am doing,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 a HTML button on my page, to add a person. As

<br />
<input id="Button1" type="button" value="AddMorePerson"        onclick="AddPerson();"/><br />

Onclick of Add button, I am fetching the data from server using Ajax call.

<br />
function AddPerson() {</p>
<p>            var inputs = new Object();<br />
            inputs.count = personCount;</p>
<p>            $.ajax({<br />
                type: "POST",<br />
                url: "Template.aspx/AddPerson",<br />
                contentType: "application/json; charset=utf-8",<br />
                data: JSON.stringify(inputs),<br />
                dataType: "json",<br />
                success: AjaxSucceeded,<br />
                error: AjaxFailed<br />
            });</p>
<p>        }<br />

After fetching the data, display it with the help of client templating., As

<br />
 function DisplayChildren(result) {</p>
<p>            var persons = eval(result.d);<br />
            personCount = persons.length;<br />
                $("#personTemplate").tmpl(persons).appendTo($("#divPerson"));<br />
        }<br />

It just append the a 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 works 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, Means an employee can
belong to multiple addresses. My employee and address class are like

<br />
public class Address<br />
{<br />
    public string Street { get; set; }<br />
    public String AddressLine1 { get; set; }<br />
    public String AddressLine2 { get; set; }<br />
    public string City { get; set; }<br />
    public string Zip { get; set; }<br />
}<br />
 

and Employee class

<br />
public class Employee<br />
{</p>
<p>    public int EmployeeId { get; set; }<br />
    public String Name { get; set; }<br />
    public int Age { get; set; }<br />
    public List Addresses { get; set; } }<br />

now the webmethod that is returning the data

[WebMethod()]
    public static string GetEmployees()
    {
        List persons = new List()
        {
            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 client side, this data is displayed using templating feature.

Now at client side, My client side templates woulld be

Parent Template:

<br />
<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><br />

Child Template:

<br />
<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>

      {{/each}}
   </script><br />

As here you can see in child template, I have put the template in the tags
{{each Addresses}}{{/each}}. It just render 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 ie here list of Addresses and apply the templating on the template
AddressTemplate

Now lets run the application:

Nested Templates

Microsoft Announcements:

Around a month back, Microsoft announced three plugins as new official plugin for jQuery.
– Templating
– Datalinking
– Globalisation
New Official jQuery Plugins Provide Templating, Data Linking and Globalization

In 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 my this article, I discussed Templating and in my upcoming articles I will be talking about Datalinking and Globalization.

Conclusion:

As I already discussed in Introduction section, that jQuery templating provides us a very rich feature to generate the UI without writing much code and in efficient manner. So one should use templateing feature wherever possible. This feature may be very good, where we display the lot of data and also it may get updated. I used it in my application, in almost every page and found it very efficient than server side code.

Feedback and Suggestions:

Hope you all will this Article and will give your valuable feedback which will be very helpful for me to write better content next time.