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” :  [

{

“imgSrc”:”cover1.jpg”,

“title”:”Captain Templates”,

“year”:”2010″,

“number”:”1″

},

{

“imgSrc”:”cover2.jpg”,

“title”:”Captain Templates”,

“year”:”2011″,

“number”:”2″

},

{

“imgSrc”:”cover3.jpg”,

“title”:”Captain Templates”,

“year”:”2012″,

“number”:”3″

}

]

}

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>

<html>

<head>

<meta charset=”utf-8″>

</head>

<body>

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

</script>

<script>

$(function(){

var populate = function( data ){

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

}

$.ajax({

type :  ‘get’,

url :  ‘data.json’,

success : populate, dataType : “json”

});

}

);

</script>

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

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

<div class=”details”>

<div class=”title”>

<h3>${title}</h3>

</div>

<div class=”year”>

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

</div>

<div class=”number”>

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

</div>

</div>

</div>

</script>

</body>

</html>

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 *