To minimize the amount of code that has to be written for an application, nearly every programming language uses templates in some manner. You can define a template structure one time and use it to generate code, HTML, or other formats. If you've created ASP.NET applications, you already know how powerful and productive templates are when it comes to rendering HTML. For example, you may have used an item template similar to the following in a ListView or other type of server control:

                              <ItemTemplate>                                  <div>                                              <div class="floatLeftRow"><%#Eval("CustomerID") %></div>                                              <div class="floatRightRow"><%#Eval("CompanyName") %></div>                                  </div>                              </ItemTemplate> 

Wouldn't it be nice if you could follow the same process on the client side? Well, if you're working with JavaScript Object Notation (JSON) objects, you certainly can.Although templates have been available in script libraries for some time through the use of various plug-ins, the latest template framework that was created jointly by Microsoft and the jQuery team provides a great solution that doesn't use Cascading Style Sheets (CSS) in strange ways or require a lot of knowledge about a template language. By using this framework, you can define HTML templates in web pages and use them to render HTML output dynamically at runtime simply by passing a JSON object into a template function. This process is extremely easy to use and very productive. Ultimately, it also means there's much less JavaScript code that you have to write and maintain.

Defining a Template Block

To get started using jQuery template functionality, you'll need to download the jquery.tmpl.js script plug-in files, available on the GitHub Social Coding website. (The plug-in was in beta when this article was being written.) To define a template, you reference the template script in your web page, then define a <script> block in your page by specifying the type as text/x-jquery-tmpl, as shown in the following code example:

                              <script id="OrderSummaryTemplate" type="text/x-jquery-tmpl">                                  <!-- Template goes here –->                              </script>                               

After you define the script tag, you can put template code within it. Any HTML that you add is output automatically after the template is rendered. Of course, adding static HTML doesn't accomplish much. Therefore, the jQuery Templates plug-in provides a template tag language. This language contains several tags that you can add to a template to perform many different tasks, such as defining data that should be generated as output, performing conditional logic, iterating through items, and rendering nested templates.

jQuery Templates TagsThe jQuery Templates plug-in defines several different tags that can be embedded in a template and that are used to control the type of data rendered. I'll introduce you to the different template tags that are available, and demonstrate how to use them.

${ PropertyName } tag. This is arguably the most useful tag you'll use within a template, and one that you'll find yourself using over and over. This tag is similar to the <%# Eval("PropertyName") %> data-binding expression that you use to bind properties within ASP.NET server control templates. This tag is responsible for evaluating the specified property on the current data item and for writing out the property. You can also wrap a JavaScript function around the property in situations in which the data must be manipulated in some way. The following code shows this tag in use:

                               <script id="SampleTemplate" type="text/x-jquery-tmpl">                                  <div>${ DeliveryFee }</div>                              </script>

If the value of the DeliveryFee property is $5.00, for example, the output is generated as follows after the template is rendered:


{{ html PropertyName }} tag. This tag is used to handle data that may contain HTML markup, such as <span style="font-weight:bold;">My Comment. Whereas the ${ PropertyName } template tag encodes data, the {{ html PropertyName }} tag doesn't encode the text as it's added into the HTML Document Object Model (DOM). The following code shows this tag in use:

                               <script id="CommentsTemplate" type="text/x-jquery-tmpl">                                  <h4>${Name}</h4>                                  <p>{{html Comment }}</p>                              </script>

{{ if }} tag. This tag is fairly common, and it's especially useful if you have to generate output data or markup that's based on one or more conditions. This tag can be used to evaluate a condition and render content, as appropriate. As with most programming languages, the {{ if }} tag can be associated with an {{ else }} tag in cases where multiple conditions are tested. Figure 1 shows this tag in use.

  1. {{if MainItems.length==0}}
  2.     <tr>
  3.         <td>No items selected</td>
  4.     </tr>
  5. {{else}}
  6.     <tr>
  7.         <td>Ordered items!</td>
  8.     </tr>
  9. {{/if}}

{{ each }} tag. This tag is used to perform looping operations within a template. For example, you may have a JSON object that contains order information, and the order information contains an array of ordered items named MainItems. You can iterate through each item by using the {{ each }} tag. The code in Figure 2 shows that the {{ each }} tag accepts an index position (i), a variable name for the current item (mi), and the name of the array to iterate through. The variable name (mi) can be used to access properties of the current item. This example renders the NumberOrdered and Price property values within a table cell.

  1. {{each(i,mi) MainItems}}
  2.     <tr>
  3.         <td>
  4.             ${ mi.NumberOrdered } ordered
  5.             at $ ${ mi.Price} per item
  6.         </td>
  7.     </tr>
  8. {{/each}}

{{tmpl}} tag. This tag is used to reference one template from within another, thereby allowing template reuse. In the example shown in Figure 3, OrderSummaryTemplate references MainItemsTemplate by using the {{tmpl '#MainItemsTemplate'}} syntax.

  1. <script id="OrderSummaryTemplate" type="text/x-jquery-tmpl">
  2.       …
  3.         <tr>
  4.             <td class="OrderHeader">Items Ordered</td>
  5.         </tr>
  6.         {{tmpl '#MainItemsTemplate' }}
  7.         <tr>
  8.             <td>&nbsp;</td>
  9.         </tr>
  10.      …
  11. </script>
  13. <script id="MainItemsTemplate" type="text/x-jquery-tmpl">
  14.     {{if MainItems.length==0}}
  15.         <tr>
  16.             <td>No items selected</td>
  17.         </tr>
  18.     {{else}}
  19.         {{each(i,mmi) MainItems}}
  20.             <tr>
  21.                 <td>
  22.                     ${ mmi.Name} - ${ mmi.NumberOrdered} ordered at $ ${ mmi.Price} per item
  23.                 </td>
  24.             </tr>
  25.         {{/each}}
  26.     {{/if}}
  27. </script>

The result is that one or more rows from MainItemsTemplate are embedded directly below the Items Ordered row within OrderSummaryTemplate. By using this technique, you can more easily reuse templates within an application or break up large templates into more manageable pieces.

{{wrap}} tag. This tag is similar to the {{ tmpl }} tag in that it lets you embed one template within another. But it also provides a way to wrap content around a specific template's content. The jQuery documentation provides an elegant yet simple example of using {{ wrap }}, which is shown in Figure 4.

  1. <script id="myTmpl" type="text/x-jquery-tmpl">
  2.     The following wraps some HTML content:
  3.     {{wrap "#tableWrapper"}}
  4.         <div>
  5.             First <b>content</b>
  6.         </div>
  7.         <div>
  8.             And <em>more</em> <b>content</b>...
  9.         </div>
  10.     {{/wrap}}
  11. </script>
  13. <script id="tableWrapper" type="text/x-jquery-tmpl">
  14.     <table><tbody>
  15.         <tr>
  16.             {{each $item.html('div')}}
  17.                 <td>
  18.                     {{html $value}}
  19.                 </td>
  20.             {{/each}}
  21.         </tr>
  22.     </tbody></table>
  23. </script>

At first glance, it may appear that the {{ wrap }} tag and the {{ tmpl }} tag are identical because both use similar syntax. However, you can see in the code in Figure 4 that the template contains a closing {{/wrap}} tag. In this example, the two <div> tags inside the myTmpl template will be wrapped inside the tableWrapper template. This means that each <div> tag will be placed inside a <td> tag. The tableWrapper template handles the placement of each <div> tag inside a <td> tag by using the $item.html('div') call within an {{ each }} loop. This puts each <div> tag inside the {{ wrap }} and {{ /wrap }} tags, and it also puts the <div> tag inside a <td> tag by using {{html $value}}.

Rendering a Template
After a template is defined by using a <script> block, you can use the jQuery Template tmpl() function to render the template to a container. You do this by determining the target template, calling tmpl, and passing a JSON object into it. The resulting HTML that's generated by the template can then be added to an existing element by using standard jQuery functions, such as appendTo or prependTo. The following is an example of the tmpl() function in use


The JSON data can either be created locally or retrieved from a remote service, as shown in Figure 5.

  1. function PlaceOrder(orderData) {
  2.     $.ajax({
  3.         url: /Orders/PlaceOrder,
  4.         dataType: 'json',
  5.         data: orderData,
  6.         success: ProcessOrder
  7.     });
  8. }
  9. function ProcessOrder(json)
  10. {
  11.       $('#OrderSummaryTemplate').tmpl(json).appendTo('#OrderSummaryOutput');
  12. }

This code uses jQuery's ajax() function to call a service that's located at /Orders/PlaceOrder and that returns JSON data containing order information. After JSON data is returned from the service, the data is passed to the ProcessOrder() function. The ProcessOrder() function then uses the tmpl() function to render a template named OrderSummaryTemplate and also appends the resulting HTML to an OrderSummaryOutput object.

Work Smarter, not Harder

You'll certainly want to put template functionality to work if you're creating dynamic web applications that leverage jQuery and AJAX. You'll find that the new jQuery Templates plug-in can significantly increase your productivity and eliminate a lot of code that you'd typically have to write. It's a great tool to have in your jQuery toolbox! Join us for our continuation in jQuery templating in "Meet JsRender -- the Next Version of jQuery Templates," where we'll show you how to minimize JavaScript coding in your HTMl5 web apps.

The sample Order Up application provided with this article illustrates how to use features that are discussed here to render HTML on the client side. You can download the code for this article at Download link at the top of this article.