Working with JQuery Templates

Most often in the web applications you use JQuery to talk to some web service, fetch the data in JSON format and write some messy code to bundle the retrieved data with the HTML tags and add it to the HTML container. JQuery templates allow a developer to write quick, effective and clean code. By using JQuery templates you can simply define a template and pass on the JSON data to it in order to generate the client HTML content.

The JQuery templates feature is available in the file jquery.tmpl.min.js, which can be downloaded from here. It works well with JQuery version 1.4.4 or greater. The method that does this template data binding in JQuery is .tmpl().

Two Different Ways to Render a JQuery Template

A JQuery template can be rendered in two different ways. You can inject the child HTML tags along with the data expression to the .tmpl() method as a string. Below is the syntax.

$.tmpl("<tr><td>${Column1}</td><td>${Column2}</td></tr>", dataObject).appendTo("#yourHtmlContainer");

You can also define a reusable template and later use it to bind the data to an HTML container control. Below is the syntax.

$("#yourTemplate").tmpl(dataObject).appendTo("yourContainerControl");

Binding the JSON Data Using a JQuery Template - Example

In this section I will take you through creating a sample web page implementing a JQuery template. Create an empty Asp.Net web application and add an HTML page named JQueryTemplateSample.Htm. Add the reference to the JQuery and JQuery template script files onto the web page. In this web page I will bind the list of employee data on to an HTML table control using a pre-defined JQuery template. Below is the code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>JUquery Template sample</title>
    <script src="Scripts/jquery-1.4.4.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.tmpl.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var employeeData = [
                { FirstName: "Rob", LastName: "Mathews", Age: 26 },
                { FirstName: "Richie", LastName: "Richards", Age: 32 },
                { FirstName: "Shawn", LastName: "Clarke", Age: 53 },
                { FirstName: "Dave", LastName: "Canterburry", Age: 42 }
            ];
 
            $("#MyTemplate").tmpl(employeeData).appendTo("#employeeContainer");
        });
    </script>
    <script id="MyTemplate" type="text/x-jquery-tmpl">
        <tr>
            <td>${FirstName}</td>
            <td>${LastName}</td>
            <td>${Age}</td>
        </tr>
    </script>
</head>
<body>
    <table>
        <thead>
            <th>
                First Name
            </th>
            <th>
                Last Name
            </th>
            <th>
                Age
            </th>
        </thead>
        <tbody id="employeeContainer">
        </tbody>
    </table>
</body>
</html>

I have defined a static JSON employee data having the fields FirstName, LastName and Age. The template should be defined under the script tag with type as “text/x-jquery-tmpl”. This is a special type that allows JQuery to understand that it is a template definition. Run the web page and Fig 1.0 shows the data bound to the table.

Fig 1.0: JUquery Template Sample
Fig 1.0: JUquery Template Sample

Inside the template definition you can also make use of the ${{each}} tag to loop through the data and ${{if}} tag to implement an if/else condition. Below is the sample code where I can show the seniority based on the age of the employee using ${{if}}.

<script id="MyTemplate" type="text/x-jquery-tmpl">
        <tr>
            <td>${FirstName}</td>
            <td>${LastName}</td>
            <td>${Age}</td>
            <td>{{if Age > 40}}
                    Yes
                {{else}}
                    No
                {{/if}}
            </td>
        </tr>
</script>

Now say you want the FirstName and LastName to be concatenated and shown as a single column EmployeeName then you can define a javascript function to concatenate two strings and call the function inside the template as shown below.

<script type="text/javascript">
        function GetName(firstName, lastName) {
            return firstName + " " + lastName;
        }
</script>
<script id="MyTemplate" type="text/x-jquery-tmpl">
        <tr>
            <td>${GetName(FirstName, LastName)}</td>
            <td>${Age}</td>
            <td>{{if Age > 40}}
                    Yes
                {{else}}
                    No
                {{/if}}
            </td>
        </tr>
</script>

Hope this article provided a good jump start for you to start working on the JQuery templates. Though this JQuery Templating feature works like a charm I am not sure why the JQuery team does not want this to go beyond the beta version. You can find more information related to it here.

Happy reading!



Related Articles

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds