jTemplates with jQuery, AJAX and Json

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">  {#foreach $T.result as project}      {#/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}    {#foreach $T.result as task}     {#include ROW root=$T.task}   {#/for}
ID Task Hours
 {#/template MAIN}  {#template ROW}    {$T.id}   {$T.name}   {$T.hours}  {#/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


Trả lời

Mời bạn điền thông tin vào ô dưới đây hoặc kích vào một biểu tượng để đăng nhập:

WordPress.com Logo

Bạn đang bình luận bằng tài khoản WordPress.com Đăng xuất /  Thay đổi )

Google+ photo

Bạn đang bình luận bằng tài khoản Google+ Đăng xuất /  Thay đổi )

Twitter picture

Bạn đang bình luận bằng tài khoản Twitter Đăng xuất /  Thay đổi )

Facebook photo

Bạn đang bình luận bằng tài khoản Facebook Đăng xuất /  Thay đổi )


Connecting to %s