Tuesday, September 21, 2010

jQuery Templating

To integrate UI control and the data it is representing is always a challenge. Asp.Net has data binding feature which perfectly works. But with Ajax type application, data rendering should be conducted from client side. MS lately has a jQurey plugin, it is a cute solution for client data binding.

Instead of:

var clRec = "";
for(var i=0; i<client.name.length; i++) {
clRec += "<li><a href='clients/"+client.id[i]+"'>" + client.name[i] + "</a></li>";
}

It is a lot better:

<li><a href="clients/${id}">${name}</a></li>

The better way is actually showing a templete. There are two things that have to be done first to make a template work: define a data instance that is to be bound to the template; and determine the data instance is a singlar data or a collection, so as to determine a loop of the template is needed to render the template.

MS jQuery Template plugin solution

To have reference:

<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script src="jquery.tmpl.js" type="text/javascript"></script>

To define data instance:

var clientData = [
{ name: "Rey Bango", id: 1 },
{ name: "Mark Goldberg", id: 2 },
{ name: "Jen Statford", id: 3 }
];


To define template
<script id="clientTemplate" type="text/html">
<li><a href="clients/${id}">${name}</a></li>
</script>

To specify data binding:

$("#clientTemplate").tmpl(clientData).appendTo( "ul" );

appendTo is to hook the html tag where the rendered template result will apply.

An example (courtesy of [1])

<html>
<head>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script src="jquery.tmpl.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {
var clientData = [
{ name: "Rey Bango", id: 1 },
{ name: "Mark Goldberg", id: 2 },
{ name: "Jen Statford", id: 3 }
];

$("#clientTemplate").tmpl(clientData).appendTo( "ul" );
});
</script>

<script id="clientTemplate" type="text/html">
<li><a href="clients/${id}">${name}</a></li>
</script>
</head>
<body>

<ul></ul>

</body>
</html>


1. http://blog.reybango.com/2010/07/09/not-using-jquery-javascript-templates-youre-really-missing-out/

No comments: