Easy Client Side Repeater With jTemplates
In this post I would like to show you how easy you can implement client side repeater. There are a few jQuery plugins which you can use for it. However I recommend using jTemplates. With jTemplates you can easily define a client side templates, here is an example:
<p style="display:none"><textarea id="EventsTemplate" rows="0" cols="0"><!--
<table>
<thead>
<tr>
<th>Event</th>
<th>Contact</th>
<th>Venue</th>
</tr>
</thead>
<tbody>
{#foreach $T.d as record}
<tr>
<td><a href="{$T.record.WebSite}">{$T.record.Name}</a></td>
<td>
<a href="mailto:{$T.record.Organizer.Email}">
{$T.record.Organizer.Name}
</a>
</td>
<td>{$T.record.Venue.Name}</td>
</tr>
{#/for}
</tbody>
</table>
--></textarea></p>
In the above example you can see that template itself is hidden for end users (display:none). Everything within HTML comments will be used. You can easily recognize elements corresponding to well known ASP.NET Repeater elements:
- everything from the very top (<table>) to {#foreach … } represents HeaderTemplate
- everything between {#foreach…} and {/#for} represents ItemTemplate
- and everything under {/#for} is a FooterTemplate
How to Bind Data to Client Side Repeater?
JS code binding data to the jTemplates repeater looks like this:
BindDataToEventsTemplate = function (result) {
// attach and process the template
$("#Events").setTemplateElement("EventsTemplate");
$("#Events").processTemplate(result);
}
Where $(“Events”) selects tag with id “Events” – this is where output will be placed. “EventsTemplate” is the name of our template – check the definition of template (first piece of code). So it’s that easy – firstly you need to set template which you want to use and secondly bind the data and ”process template”. End of story!
Just to make everything perfectly clear – here is an example of my “Events” tag where new events will be added using client side repeater:
<div id="Events"></div>
One additional tip – you can also check, just in case, if jTemplates has been correctly loaded by adding this piece of code:
// check if jTemplates is loaded
if (!jQuery.fn.processTemplate) {
alert("jTemplates is not loaded");
return;
}
In my case I have loaded data to the repeater from ASP.NET WebService. In the next post I will show you how to get it all working together – jTemplates with ASP.NET WebServices.
[...] is the third post in “Easy Client Side Repeater with jTemplates” series. Just to recap quickly – last two posts were [...]
Easy Client Side Repeater with jTemplates Part 3 | jQuery with ASP.NET
6 Apr 11 at 11:27 pm