Introduction to jQuery Templates

About two weeks ago I’ve had around two hours long session at MKDOT.NET UG monthly meeting on subject “Deep Dive into jQuery Templates in ASP.NET”. Now, I will try to split up few parts of the presentation and write some blogs here.

 

Templates in General

In general, template is a form, model, sample or predefined shape used to provide consistent look and feel to information presented on a website. In the technology areas, templates are almost everywhere. You have templates in programming languages, word processing, games, design etc etc.

 

Web Templates

The first association to templates I always have in my mind are the Web Templates. The purpose of the web templates is same as explained in Templates in General. You create a consistent look and feel for your website and apply data to it, so all pages will have the same look and feel. For web templates, we mainly use CSS (Cascade Stylesheet), HTML/XHTML, Skins, MasterPages etc.

 

Templates in ASP.NET

We also have templates in ASP.NET. If you’ve been working with ASP.NET WebForms, you have probably been working with any (or all) of the following: Repeater, FormView, GridView, DataList, DetailsView.
In ASP.NET MVC you probably use Html Helpers… All these are some kind of predefined templates.

 

jQuery Templates

jQuery Templates are client-side based templates.

The benefits of using jQuery Templates are:

  1. Easily convert JSON object to HTML without need for parsing
  2. Reusability
  3. Rendered and cached on client-side
  4. Templates are written in pure HTML with Template Tags and simple jQuery code for magic to happen
  5. Maximize the separation of UI and DATA

jQuery Templates is an official plugin for the jQuery Library and is the 1st Microsoft Contribution to the jQuery Project. It’s interesting to note that jQuery Templating plugin will be added inside the jQuery v1.5 core library so that you won’t need to reference separate script for the templates to work. You also have the scripts in the Microsoft CDN (development version | minified production version).

How do jQuery Templates work?

Mainly, the jQuery Template is applied to data objects or arrays and is rendered into the HTML using jQuery functions for DOM manipulation. The data objects/arrays are JSON data format. For those that don’t know, JSON stands for JavaScript Object Notation and is very lightweight data-interchange format. JQuery Template is for JSON data same as XSLT is for XML data.


 

Simple Example

var myTemplate = "<li> ${name} </li>";

or the same can be written in the following way:

<script id="myTemplate" type="text/html">
    <li> ${name} </li>
</script>

The difference is that in the second example, we have the template wrapped in <script /> tag adding an ID and type=”text/html”. This way inside script we can create very complex templates and use them only by the ID of the script block.

Let’s see a complete example.

Basic ExampleSession Attendees

1. First of all we are adding reference to the jQuery Core library and jQuery Templates library.
Note: From jQuery v1.5, we will need only the jQuery Core library since the jQuery Templates plugin will be inside it.

<script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.tmpl.js" type="text/javascript"></script>

You can see I have “../../” since my web page is not in the root directory but inside folders /Views/Templates/Basic.aspx and the scripts are placed inside Scripts/ which is on the root directory of the project.

Next, I have the following data

    var attendees = [
    { Name: "Hajan", Surname: "Selmani", Age: 25 },
    { Name: "Stojan", Surname: "Stojanov", Age: 38 },
    { Name: "Emma", Surname: "Smith", Age: 40 },
    { Name: "Adam", Surname:"Anderson", Age: 27}
];

Now, I want to show the data somehow in the HTML. I will create ordered list inside the <body> … </body> of my webpage.

<body>
    <ol id="attendees"></ol>
</body>

So, I have only the ol html element with given ID and nothing more…

Next, I will need to create the template defining how I want to show the data

<script id="attendeesTemplate" type="text/html">
    <li> ${Name} ${Surname}
    {{if Age>30}}
        (<span style='color:red'>Middle-aged</span>)
    {{else}}
        (<span style='color:blue'>Still young</span>)
    {{/if}}
    </li>
</script>

I’ve defined script block with id attendeesTemplate of text/html type. Inside the script, I have all the data wrapped in li html element. As you can see, we use ${ } to get the data from the JSON string. In this example, I have one if/else statement where I’ve put some logic on what to display for those having Age greater than 30 and else for the rest.

At the end, the magic is done by connecting the attendees data with attendeesTemplate using the tmpl() function.

$("#attendeesTemplate").tmpl(attendees).appendTo("#attendees");

It does the following: "Find the attendeesTemplate render it with attendees data and append it to HTML element with id #attendees (the ol element)”

The complete code is:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Introduction to jQuery Templates</title>
    <script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery.tmpl.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $(function () {
            var attendees = [
            { Name: "Hajan", Surname: "Selmani", Age: 25 },
            { Name: "Stojan", Surname: "Stojanov", Age: 38 },
            { Name: "Emma", Surname: "Smith", Age: 40 },
            { Name: "Adam", Surname:"Anderson", Age: 27}
        ];

            $("#attendeesTemplate").tmpl(attendees).appendTo("#attendees");
        });
    </script>
    <script id="attendeesTemplate" type="text/html">
        <li> ${Name} ${Surname}
        {{if Age>30}}
            (<span style='color:red'>Middle-aged</span>)
        {{else}}
            (<span style='color:blue'>Still young</span>)
        {{/if}}
        </li>
    </script>
</head>
<body>
    <ol id="attendees"></ol>
</body>
</html>

and the result is

Many others have already written good articles and blogs introducing jQuery Templates.

So far I've seen the following links related to this topic:
jQuery Templates and Data Linking (and Microsoft contributing to jQuery) by Scott Guthrie
An Introduction to jQuery Templates by Stephen Walther
Introducing jQuery Templates 1: First Steps by Boris Moor
Not Using jQuery JavaScript Templates? You’re Really Missing Out. by Rey Bango

This is one more attempt to spread the word about this great plugin. The next blogs I will write will explain some more of jQuery templates regarding the syntax, tags and some interesting examples using client-side data and server-side data retrieved from database.

Hope this is helpful and interesting to you.

Regards,
Hajan

NEXT - jQuery Templates - tmpl(), template() and tmplItem()

9 Comments

  • Great little article! How about using XML as the datasource instead of JSON? Same procedure I guess? :)

  • What if my JSON is returned from a URL out there? How can I get it from the URL into HTML **and** how to also convert the JSON date format (ex: # date_created: "/Date(1294003506853-0700)/") to a readable MM/DD/YY HH:MM:SS format?

  • @Mortensen, I think the best would be to serialize your into JSON object and just process the json object using tmpl(jsonObject) and that's it. Templates are primarily created to work with JSON objects.

    As I said in this post "JQuery Template is for JSON data same as XSLT is for XML data."

  • @Mike, you can take a look at my 'jQuery Templates with ASP.NET MVC' where I use $.getJSON(url, params, callbackFunction) so you can specify URL which will return JSON string. Moreover, you can use the $.ajax() jQuery method on the following way:

    $.ajax({
    type: 'GET', dataType: 'jsonp', url: 'your-url-link-here',
    success: function(data) {
    //render template to data object here
    }
    });

    As for date format conversion, if you have the date in the following format: "1294003506853-0700" you can create custom function that will create date string and you can call the function from inside template like ${FormatDate(date_created)}

    Try with this function:
    function FormatDate(jDate) {
    alert("jDate:" + jDate);
    var date = eval(jDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
    alert(date);
    var dDate = new Date(date);
    alert(dDate);
    var year = dDate.getFullYear();
    alert(year);
    return dDate;
    }

    I added some alerts to show you what you get with each line, you can freely remove the alerts ;).

    Hope this helps

  • hi is it there any way to get the only changed objetcs
    suppose for attendees i have modified only tow attends when i click on save i want only that two attend how to do this

  • @Craig, did you try this in VS.NET environment? It works fine for me. Maybe its something related to the jsfiddle... I am not sure. Let me try it and I will get back to you by the end of the day.

    Thanks.

  • @Craig, create sample project and new web form in VS.NET and add this code:





    ...



    $(document).ready(function () {
    var test =
    {
    Id: '43000796568231937',
    created_at: '1294003506853-0700'
    };

    $("#myTemplate").tmpl(test).appendTo("#tblMyTable");

    });

    function FormatDate(jDate) {
    alert("jDate:" + jDate);
    var date = eval(jDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
    alert(date);
    var dDate = new Date(date);
    alert(dDate);
    var year = dDate.getFullYear();
    alert(year);
    return dDate;
    }



    ${Id} - ${FormatDate(created_at)}










    This works very nice for me.

  • Ya know, I ended up trying it directly in VS and it worked fine. Must have been a jsfiddle problem.

    thanks!

  • Ahh... I didn't even tried transfering the code from one to another window in jsfiddle :)... I knew it works fine when added into VS.NET (or even notepad ;) ) so I already thought its something related to jsfiddle :).

    Thanks for your nice feedback.

Comments have been disabled for this content.