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:

<div>$5.00</div>

{{ 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.

Figure 1: Using the {{ if }} tag to generate output data based on conditions
{{if MainItems.length==0}}
    <tr>
        <td>No items selected</td>
    </tr>
{{else}}
    <tr>
        <td>Ordered items!</td>
    </tr>
{{/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.

Figure 2: Using the {{ each }} tag to perform looping operations
{{each(i,mi) MainItems}}
    <tr>
        <td>
            ${ mi.NumberOrdered } ordered
            at $ ${ mi.Price} per item
        </td>
    </tr>
{{/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.

Figure 3: Using the {{ tmpl }} tag to embed a child template within a parent template
<script id="OrderSummaryTemplate" type="text/x-jquery-tmpl">
      …
        <tr>
            <td class="OrderHeader">Items Ordered</td>
        </tr>
        {{tmpl '#MainItemsTemplate' }}
        <tr>
            <td>&nbsp;</td>
        </tr>
     …
</script>

<script id="MainItemsTemplate" type="text/x-jquery-tmpl">
    {{if MainItems.length==0}}
        <tr>
            <td>No items selected</td>
        </tr>
    {{else}}
        {{each(i,mmi) MainItems}}
            <tr>
                <td>
                    ${ mmi.Name} - ${ mmi.NumberOrdered} ordered at $ ${ mmi.Price} per item
                </td>
            </tr>
        {{/each}}
    {{/if}}
</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.

Figure 4: Using the {{ wrap }} tag to wrap content within a template
<script id="myTmpl" type="text/x-jquery-tmpl">
    The following wraps some HTML content:
    {{wrap "#tableWrapper"}}
        <div>
            First <b>content</b>
        </div>
        <div>
            And <em>more</em> <b>content</b>...
        </div>
    {{/wrap}}
</script>

<script id="tableWrapper" type="text/x-jquery-tmpl">
    <table><tbody>
        <tr>
            {{each $item.html('div')}}
                <td>
                    {{html $value}}
                </td>
            {{/each}}
        </tr>
    </tbody></table>
</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

$('#OrderSummaryTemplate').tmpl(json).appendTo('#OrderSummaryOutput');

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

Figure 5: Retrieving JSON data using the jQuery ajax() function and rendering it using the tmpl() function
function PlaceOrder(orderData) {
    $.ajax({
        url: /Orders/PlaceOrder,
        dataType: 'json',
        data: orderData,
        success: ProcessOrder
    });
}
function ProcessOrder(json)
{
      $('#OrderSummaryTemplate').tmpl(json).appendTo('#OrderSummaryOutput');
}

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.