Webistrate - Draw Your Own Conclusions

jQuery: Creating templates for your HTML Content

Posted by Jamie Munro | September 1, 2011 | Tags:

Share

When you have a lot of AJAX calls on your website, especially ones that return a list of data, it can be quite expensive processing time on the server to retrieve the results, format them with HTML, and return them to the browser to display – not only that, your bandwidth costs can be quite high as well.  With jQuery templates, you can alter your AJAX calls to return JSON, and then populate the content client-side providing faster response times and less server processing as well.

If you already have a lot of AJAX calls that return HTML, do not fear; it is not a lot of work to convert them to jQuery templates and improve the speed of your website.  If you are just getting started, glad to see you’re thinking ahead!

Assumptions

  • You have some basic jQuery experience
  • You have or will build a website that will populate the content for the jQuery template

To get started using jQuery templates you must have both the core jQuery API and the jQuery template API:

Be sure to check jQuery’s website to retrieve the latest versions of these items.

The purpose of a jQuery template is to bind a Javascript object or array of items to HTML that contains one or more keys that will be replaced with the content being provided.

There are a few different ways to go about implementing a jQuery template.  You can do it as a one-time expression (not really that useful, unless you are doing something simple).  You can create a variable with your template and later store it in a named template (useful for simple HTML, might not be very readable if you need to make alterations to the HTML later).  Or you can use inline markup (this is my preference as it is quite readable and works well in MVC structures where the inline markup can be contained in a partial view).

Solution 1 – One-time Expression

<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
</head>

<body>
<div id="myContent"></div>

<script>
$(document).ready(function() {
$.tmpl( "${Title}", { "Title" : "Welcome to Webistrate" }).appendTo( "#myContent" );
});
</script>
</body>
</html>

This is quite a basic example, but as you can see, I am replacing the variable Title with Welcome to Webistrate and appending it to the div with the id of myContent.

Solution 2 – Javascript Variable with the Template

<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
</head>

<body>
<div id="myContent"></div>

<script>
$(document).ready(function() {
// Content to be replaced by the template
var myContent = { Title: "Welcome to Webistrate", SubTitle: "Draw Your Own Conclusions"};

// Create the variable with the HTML markup
var myTemplate = '<h1>${Title} - <span>${SubTitle}</span></h1>';

// Store it as a named template
$.template("myTemplate", myTemplate);

// Use the template
$.tmpl("myTemplate", myContent).appendTo("#myContent");
});
</script>
</body>
</html>

This example contains slightly more complicated HTML markup where it has a header and span that contains a Title and SubTitle that is replaced with the values contained in the myContent Javascript variable.

Solution 3 – Inline Markup

<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
</head>

<body>
<div id="myContent"></div>

<script>
$(document).ready(function() {
// Content to be replaced by the template
var myContent = [
{Thumbnail: "image.jpg", Name: "Jamie", Bio: "Some info about me"},
{Thumbnail: "image2.jpg", Name: "You", Bio: "Some info about you"}
];

// Use the template
$("#myTemplate").tmpl(myContent).appendTo("#myContent");
});
</script>

<script id="myTemplate" type="text/x-jquery-tmpl">
<div class="profile">
<div class="thumbnail"><img src="${Thumbnail}" alt="" /> </div>
<div>
<span>${Name}</span>
<p>${Bio}</p>
</div>
</div>
</script>
</body>
</html>

In the above solution, an array of data is being set this time that will be populated by the template.  As you can see in the template it contains several div tags that would display a user’s thumbnail image, their name, and their bio.  Each element in the array will be appended to the myContent div with this profile information – which leads to the final example, using it with AJAX.

Simple AJAX Example

<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>
</head>

<body>
<div id="myContent"></div>

<script>
$(document).ready(function() {
$.ajax({
dataType: "jsonp",
url: "replace_with_your_url_that_returns_json",
jsonp: "$callback",
success: showData
});
});

function showData(data) {
// Use the template
$("#myTemplate").tmpl(data).appendTo("#myContent");
}
</script>

<script id="myTemplate" type="text/x-jquery-tmpl">
<div class="profile">
<div class="thumbnail"><img src="${Thumbnail}" alt="" /> </div>
<div>
<span>${Name}</span>
<p>${Bio}</p>
</div>
</div>
</script>
</body>
</html>

This final example is almost identical to the 3rd solution.  However, instead of using a hard-coded Javascript array with the content, an AJAX request is performed that will return the same array of data.  Once the AJAX request is completed successfully, showData function is called which executes the template with the data returned from AJAX.

Summary

jQuery templates are an excellent way to move the formatting of data from the server on to the client – helping to improve page load times and reduce the bandwidth and processing time on the web server.  In all of the above examples, the data was always appended to a specific element.  If you wish to not use append, the following options are also available: .appendTo, .prependTo, .insertAfter or .insertBefore.

Share


Related Posts

2 Responses to “jQuery: Creating templates for your HTML Content”

  1. [...] JSON data.  This JSON data is then parsed in Javascript and I’m strongly leveraging Jquery templates to display the data in a pretty [...]

  2. [...] another view.  This is a very neat feature; it’s actually quite similar to the concept of Jquery templating.  The concept behind it is relatively straight forward.  You define one view that contains common [...]

Leave a Reply

You must be logged in to post a comment.

Buy one of my books