jTemplates is a jQuery plugin and template engine for Javascript.  If you keep up with Dave Ward and/or Rick Strahl you may already be familiar with jTemplates as they have both highlighted the plugin on their respective bolgs.  About 1.5 months ago, however, I got into the action and started using jTemplates in conjunction with jQuery, AJAX and Json to dynamically populate dropdowns and tables on the client side.

As you’ll see in the examples, jTemplates provides custom syntax to do such things as iterate through Json data and populate a predefined template.  Once you get a grasp of the syntax and the proper usage, you will be ready to roll.  Getting started is easy — just download the latest jQuery and jTemplate bits and reference them within your html or aspx file.

Next, you need to define and host your templates.  In the included sample project, I’ve defined two templates to aid in the population of my dropdown and my table respectively.  Here you will notice the dropdown template merely adds a singe “Select One” entry and then iterates over all project results adding a new option for each:

<%-- Project Dropdown Template --%>
<script type="text/html" id="TemplateProjectSelect">
<option value="">Select One</option>
{#foreach $T.result as project}
    <option value="{$T.project.id}">{$T.project.name}</option>
{#/for}
</script>

And the following table template is a little more complex but still very to interpret.  Here, we are iterating over each task row and appending a new row to the table for each.  Notice there’s a MAIN template and a ROW template.  The MAIN template passes along the current record to the ROW template.  The ROW template sets the appropriate class (think table zebra stripes) and column values based on the current “cycle.”

<%-- Results Table Template --%>
<script type="text/html" id="TemplateResultsTable">
{#template MAIN}
<table width="500" border="0" cellpadding="5" cellspacing="0">
  <tr>
    <th width="50">ID</th>
    <th width="300">Task</th>
    <th width="104">Hours</th>
  </tr>
  {#foreach $T.result as task}
    {#include ROW root=$T.task}
  {#/for}
</table>
{#/template MAIN}

{#template ROW}
<tr class="{#cycle values=['','evenRow']}">
  <td>{$T.id}</td>
  <td>{$T.name}</td>
  <td>{$T.hours}</td>
</tr>
{#/template ROW}
</script>

How’s about hosting the templates?  You have a few options.  First, you could save the templates off in their own file.  This is the approach Dave Ward took in his article. Though this approach is clean, it doesn’t perform all that well.  The preferred approach is to “embed” your templates within the html/aspx file by wrapping each of the above templates with a script tag like so:

<script type="text/html" id="TemplateResultsTable"> 

... template here ...

</script> 

As shared on Rick Strahl’s post, this is the preferred approach as using <script type=”text/html”> that allows hiding any markup in the document without interfering with HTML validators. The script can be accessed by its ID and the content retrieved using the jQuery .html() syntax.

Once your template is in place, you simply need to assign your template to your container (a div) and then process the template using your Json data.  As noted above, you may reference an external template using the following:

$('#tasks').setTemplate('Template.htm');

Or you may select the template from the html/aspx itself:

$('#tasks').setTemplate($("#TemplateResultsTable").html());

Again, the preferred approach is the latter.  In either case, you process the template data (results) as follows:

$('#tasks').processTemplate(results);

A quick note on .processTemplate.  You don’t actually have to provide any data.  You can send null into the processTemplate method if, for example, no processing is required.  In the downloadable example, I create a static template which acts as a place holder when my page first loads and no table data is available. Here’s the sample template and javascript:

<%-- Emtpy Table Template --%>
<script type="text/html" id="TemplateResultsEmpty">
Select a client and project...
</script>

$('#tasks').setTemplate($("#TemplateResultsEmpty").html());
$('#tasks').processTemplate(null);

Before I wrap things up, I should mention the downloadable sample project doesn’t only show off jTemplates.  It also demonstrates how to use jQuery and an “parameterized” HTTPHandler to pull back Json data which is somewhat an extension of my earlier HTTPHandler post.

Download jTemplates Sample Project: jTemplates.zip

 

kick it on DotNetKicks.com

8 Responses to “jTemplates with jQuery, AJAX and Json”

  1. great article– i hadn’t thought of using the script tag to hold the jTemplates template. thanks!

  2. Thanks for the feedback, Micah.

  3. Are you sure you can set an external template with: $(’#tasks’).setTemplate(’Template.htm’);?

    It does not work for me.

  4. @Jonatán Rueda - I thought it worked, but I took a look at the documentation this morning (http://jtemplates.tpython.com/) and I found that setTemplateURL download a template from url and assigns to HTML element(s). So, you what I’ve references may be incorrect. I’ll see if I can put together a sample and verify later. Let me know what you find out please. Thanks for the question!

  5. Hi Ben, thanks for the article, its very interesting.

    Ive recently written a similar article about jTemplates that also includes code examples for creating a web service with WCF.

    You can find it here: Tying in WCF, JSON and jTemplates

  6. This is a gr8 article and i have used in my project.
    I have one query here. I have used web service which returns user’s date, which i am binding with the TemplateResultsTable to display tabular data and its working fine.
    However I also want to display image of user (image url come from web service data). Image url comes with tild sign(~), which does not work with simple html tags. so how i can create image tag here?
    I have tried following code but it does not work.
    “”

  7. Hi,

    I want to list jtemplate table to a dropdown list and chnage in list value would pull data from webservice to populate table.

    It works fine for the first time but second time it gives error at settemplate stage. error is “Microsoft JScript runtime error: ‘constructor’ is null or not an object”

    is there any way to dynamically set template based on dropdown list . Please advise.

Trackbacks/Pingbacks

  1. Arjan`s World » LINKBLOG for December 19, 2008

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>