jQuery Templates: Applying Templates with $.tmpl()

Once you’ve created your site’s templates, it’s time to start using them in your pages. You have two different contexts from which to apply templates.

If you’ve created your templates inline, you can pass a selector representing the script tag holding your template. This is illustrated in the following code sample. In it, you have a template tag with the id #comics. To apply it, you get a reference to it using the id selector and then you call the $.tmpl() method, passing the comics array as an argument. Then it’s simply a matter of calling $.appendTo() to insert it into the document.

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

}];

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

}

);

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

${year}

</div>

<div class=”number”>

${number}

</div>

</div>

</div>

</script>

</body>

</html>

Code snippet is from inline.html

This page produces the output shown in Figure 11-1.

The second method is to use compiled templates. Pass the name of a template created with $.template() into jQuery.tmpl() along with a data object, and it will be applied in exactly the same way.

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

}];

$.template( ‘comics’ , ’<div class=”comic”>

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

<h3>${title}</h3></div><div class=”year”>${year}</div>

<div class=”number”>${number}</div></div></div>’ );

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

);

</script>

</body>

</html>

Code snippet is from template-method.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 *