About 2 years ago (November 2007) I wrote a small JavaScript function to request JSON data from a URL and bind the results to a client-side, HTML-resident template. I used it a demo piece, showing that even though our platform product used (server-side) templates to render it's markup, those template could contain anything, such as JSON to push to a client. There are quite a few of these around now, but I'm still using my own as it's small, I understand how it works (I hope) and recently I used it as an excuse to get into jQuery plugin authoring, modifying my adhoc function to become a plugin. Here are the quickstart four steps to using it and a full example download can be found at the bottom of the page (as soon as I've uploaded it).
Step 1 : Include Required Libraries
<script type="text/javascript" src="/scripts/jquery-1.3.2.min.js">
<script type="text/javascript" src="/scripts/jquery.templatebinder.js">
Step 2 : Add Destination Markup
This basically means, when do you want the bound template contents to end up? I usually include an empty <div>.
<div id="template_destination"></div>
Be sure to include both opening and closing tags, so that the innerHtml can be targeted.
Step 3: Define Your Templates
The trick to including templates in HTML is to prevent the browser thinking they are HTML. Typically, templates are fragments of HTML and therefore unlikely to be compliant. For instance, partial tables, <TR> rows, etc. So, thanks to John Resig for this next tip:
<script type="text/html" id="table_header">
<table>
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>Date Of Birth</th>
</tr>
</thead>
<tbody>
</script>
<script type="text/html" id="tablerow_template">
<tr>
<td><span>{{Name}}</span></td>
<td><span>{{Address}}</span></td>
<td><span>{{DateOfBirth}}</span></td>
</tr>
</script>
<script type="text/html" id="table_footer">
</tbody></table>
</script>
The header and footer elements are optional.
Step 4 : Call the Binder
$("#template_destination").templateBinder({
url: "/data/feed.json",
template: "tablerow_template",
header: "table_header",
footer: "table_footer"
});
There are a few extra options that can be passed into the binder, such as whether the template destination is first emptied. Here is a link to the code (21.94 kb).