jQuery Templates: Applying Templates Using Remote Data

Most of the examples in this chapter illustrate a JavaScript array defined in a script block for clarity, and the ability to run the examples in the browser without firing up a web server. However, most of the time, you’ll be applying templates to dynamic data retrieved from an Ajax request.

Although the template patterns are the same, it’s useful to walk through a simple example using an Ajax request to illustrate the way it might be handled.

In this example, you’ll be working with a data.json file with the following structure:


“comics” :  [



“title”:”Captain Templates”,






“title”:”Captain Templates”,






“title”:”Captain Templates”,






Code snippet is from data.json

In your script file, you simply grab the data using $.ajax and then pass the data to the success function, populate, which is set up to handle the data with .tmpl():

<!DOCTYPE html>



<meta charset=”utf-8″>



<div id=”main”> </div>

<script src=”http://code.jquery.com/jquery-1.7.1.min.js”></script>

<script src=” //ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js”>




var populate = function( data ){

$( “#comics” ).tmpl(data.comics).appendTo( “#main” );



type :  ‘get’,

url :  ‘data.json’,

success : populate, dataType : “json”





<script id=”comics” type=”text/x-jquery-tmpl”>

<div class=”comic”><img src=”${imgSrc}” />

<div class=”details”>

<div class=”title”>



<div class=”year”>

<strong>Year:</strong> ${year}


<div class=”number”>

<strong>Issue Number:</strong> ${number}







Code snippet is from ajax.txt

Source: Otero Cesar, Rob Larsen (2012), Professional jQuery, John Wiley & Sons, Inc

Leave a Reply

Your email address will not be published. Required fields are marked *