Knockout JS: Helping you build dynamic JavaScript UIs with MVVM and ASP.NET

Introduction

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. Any time you have sections of UI that update dynamically (e.g., changing depending on the user’s actions or when an external data source changes), KO can help you implement it more simply and maintainably.

Headline features:

  • Elegant dependency tracking – automatically updates the right parts of your UI whenever your data model changes.
  • Declarative bindings – a simple and obvious way to connect parts of your UI to your data model. You can construct a complex dynamic UIs easily using arbitrarily nested binding contexts.
  • Trivially extensible – implement custom behaviors as new declarative bindings for easy reuse in just a few lines of code.

Additional benefits:

  • Pure JavaScript library – works with any server or client-side technology
  • Can be added on top of your existing web application without requiring major architectural changes
  • Compact – around 13kb after gzipping
  • Works on any mainstream browser (IE 6+, Firefox 2+, Chrome, Safari, others)
  • Comprehensive suite of specifications (developed BDD-style) means its correct functioning can easily be verified on new browsers and platforms

Developers familiar with Ruby on Rails, ASP.NET MVC, or other MV* technologies may see MVVM as a real-time form of MVC with declarative syntax. In another sense, you can think of KO as a general way to make UIs for editing JSON data… whatever works for you 🙂

OK, how do you use it?

The quickest and most fun way to get started is by working through the interactive tutorials. Once you’ve got to grips with the basics, explore the live examples and then have a go with it in your own project.

Is KO intended to compete with jQuery (or Prototype, etc.) or work with it?

Everyone loves jQuery! It’s an outstanding replacement for the clunky, inconsistent DOM API we had to put up with in the past. jQuery is an excellent low-level way to manipulate elements and event handlers in a web page. KO solves a different problem.

As soon as your UI gets nontrivial and has a few overlapping behaviors, things can get tricky and expensive to maintain if you only use jQuery. Consider an example: you’re displaying a list of items, stating the number of items in that list, and want to enable an ‘Add’ button only when there are fewer than 5 items. jQuery doesn’t have a concept of an underlying data model, so to get the number of items you have to infer it from the number of TRs in a table or the number of DIVs with a certain CSS class. Maybe the number of items is displayed in some SPAN, and you have to remember to update that SPAN’s text when the user adds an item. You also must remember to disable the ‘Add’ button when the number of TRs is 5. Later, you’re asked also to implement a ‘Delete’ button and you have to figure out which DOM elements to change whenever it’s clicked.

How is Knockout different?

It’s much easier with KO. It lets you scale up in complexity without fear of introducing inconsistencies. Just represent your items as a JavaScript array, and then use a foreach binding to transform this array into a TABLE or set of DIVs. Whenever the array changes, the UI changes to match (you don’t have to figure out how to inject new TRs or where to inject them). The rest of the UI stays in sync. For example, you can declaratively bind a SPAN to display the number of items as follows:

There are <span data-bind="text: myItems().count"></span> items

That’s it! You don’t have to write code to update it; it updates on its own when the myItems array changes. Similarly, to make the ‘Add’ button enable or disable depending on the number of items, just write:

<button data-bind="enable: myItems().count < 5">Add</button>

Later, when you’re asked to implement the ‘Delete’ functionality, you don’t have to figure out what bits of the UI it has to interact with; you just make it alter the underlying data model.

To summarise: KO doesn’t compete with jQuery or similar low-level DOM APIs. KO provides a complementary, high-level way to link a data model to a UI. KO itself doesn’t depend on jQuery, but you can certainly use jQuery at the same time, and indeed that’s often useful if you want things like animated transitions.

Knockout JS: Helping you build dynamic JavaScript UIs with MVVM and ASP.NET

Reference : http://knockoutjs.com/documentation/introduction.html

Introduction to SignalR

ASP.NET SignalR is a library for ASP.NET developers that simplifies the process of adding real-time web functionality to applications. Real-time web functionality is the ability to have server code push content to connected clients instantly as it becomes available, rather than having the server wait for a client to request new data.

SignalR can be used to add any sort of “real-time” web functionality to your ASP.NET application. While chat is often used as an example, you can do a whole lot more. Any time a user refreshes a web page to see new data, or the page implements long polling to retrieve new data, it is a candidate for using SignalR. Examples include dashboards and monitoring applications, collaborative applications (such as simultaneous editing of documents), job progress updates, and real-time forms.

SignalR also enables completely new types of web applications that require high frequency updates from the server, for example, real-time gaming. For a great example of this, see the ShootR game.

SignalR provides a simple API for creating server-to-client remote procedure calls (RPC) that call JavaScript functions in client browsers (and other client platforms) from server-side .NET code. SignalR also includes API for connection management (for instance, connect and disconnect events), and grouping connections.

Invoking methods with SignalR

SignalR handles connection management automatically, and lets you broadcast messages to all connected clients simultaneously, like a chat room. You can also send messages to specific clients. The connection between the client and server is persistent, unlike a classic HTTP connection, which is re-established for each communication.

SignalR supports “server push” functionality, in which server code can call out to client code in the browser using Remote Procedure Calls (RPC), rather than the request-response model common on the web today.

SignalR applications can scale out to thousands of clients using Service Bus, SQL Server or Redis.

SignalR is open-source, accessible through GitHub.

SignalR and WebSocket

SignalR uses the new WebSocket transport where available, and falls back to older transports where necessary. While you could certainly write your application using WebSocket directly, using SignalR means that a lot of the extra functionality you would need to implement will already have been done for you. Most importantly, this means that you can code your application to take advantage of WebSocket without having to worry about creating a separate code path for older clients. SignalR also shields you from having to worry about updates to WebSocket, since SignalR will continue to be updated to support changes in the underlying transport, providing your application a consistent interface across versions of WebSocket.

While you could certainly create a solution using WebSocket alone, SignalR provides all of the functionality you would need to write yourself, such as fallback to other transports and revising your application for updates to WebSocket implementations.

Transports and fallbacks

SignalR is an abstraction over some of the transports that are required to do real-time work between client and server. A SignalR connection starts as HTTP, and is then promoted to a WebSocket connection if it is available. WebSocket is the ideal transport for SignalR, since it makes the most efficient use of server memory, has the lowest latency, and has the most underlying features (such as full duplex communication between client and server), but it also has the most stringent requirements: WebSocket requires the server to be using Windows Server 2012 or Windows 8, and .NET Framework 4.5. If these requirements are not met, SignalR will attempt to use other transports to make its connections.

HTML 5 transports

These transports depend on support for HTML 5. If the client browser does not support the HTML 5 standard, older transports will be used.

  • WebSocket (if the both the server and browser indicate they can support Websocket). WebSocket is the only transport that establishes a true persistent, two-way connection between client and server. However, WebSocket also has the most stringent requirements; it is fully supported only in the latest versions of Microsoft Internet Explorer, Google Chrome, and Mozilla Firefox, and only has a partial implementation in other browsers such as Opera and Safari.
  • Server Sent Events, also known as EventSource (if the browser supports Server Sent Events, which is basically all browsers except Internet Explorer.)

Comet transports

The following transports are based on the Comet web application model, in which a browser or other client maintains a long-held HTTP request, which the server can use to push data to the client without the client specifically requesting it.

  • Forever Frame (for Internet Explorer only). Forever Frame creates a hidden IFrame which makes a request to an endpoint on the server that does not complete. The server then continually sends script to the client which is immediately executed, providing a one-way realtime connection from server to client. The connection from client to server uses a separate connection from the server to client connection, and like a standard HTML request, a new connection is created for each piece of data that needs to be sent.
  • Ajax long polling. Long polling does not create a persistent connection, but instead polls the server with a request that stays open until the server responds, at which point the connection closes, and a new connection is requested immediately. This may introduce some latency while the connection resets.

For more information on what transports are supported under which configurations, see Supported Platforms.

Monitoring transports

You can determine what transport your application is using by enabling logging on your hub, and opening the console window in your browser.

To enable logging for your hub’s events in a browser, add the following command to your client application:

$.connection.myHub.logging = true;

  • In Internet Explorer, open the developer tools by pressing F12, and click the Console tab.Console in Microsoft Internet Explorer
  • In Chrome, open the console by pressing Ctrl+Shift+J.Console in Google Chrome

With the console open and logging enabled, you’ll be able to see which transport is being used by SignalR.

Console in Internet Explorer showing WebSocket transport

Specifying a transport

Negotiating a transport takes a certain amount of time and client/server resources. If the client capabilities are known, then a transport can be specified when the client connection is started. The following code snippet demonstrates starting a connection using the Ajax Long Polling transport, as would be used if it was known that the client did not support any other protocol:

connection.start({ transport: 'longPolling' });

You can specify a fallback order if you want a client to try specific transports in order. The following code snippet demonstrates trying WebSocket, and failing that, going directly to Long Polling.

connection.start({ transport: ['webSockets','longPolling'] });

The string constants for specifying transports are defined as follows:

  • webSockets
  • forverFrame
  • serverSentEvents
  • longPolling

Connections and Hubs

The SignalR API contains two models for communicating between clients and servers: Persistent Connections and Hubs.

A Connection represents a simple endpoint for sending single-recipient, grouped, or broadcast messages. The Persistent Connection API (represented in .NET code by the PersistentConnection class) gives the developer direct access to the low-level communication protocol that SignalR exposes. Using the Connections communication model will be familiar to developers who have used connection-based APIs such as Windows Communcation Foundation.

A Hub is a more high-level pipeline built upon the Connection API that allows your client and server to call methods on each other directly. SignalR handles the dispatching across machine boundaries as if by magic, allowing clients to call methods on the server as easily as local methods, and vice versa. Using the Hubs communication model will be familiar to developers who have used remote invocation APIs such as .NET Remoting. Using a Hub also allows you to pass strongly typed parameters to methods, enabling model binding.

Architecture diagram

The following diagram shows the relationship between Hubs, Persistent Connections, and the underlying technologies used for transports.

SignalR Architecture Diagram showing APIs, transports, and clients

How Hubs work

When server-side code calls a method on the client, a packet is sent across the active transport that contains the name and parameters of the method to be called (when an object is sent as a method parameter, it is serialized using JSON). The client then matches the method name to methods defined in client-side code. If there is a match, the client method will be executed using the deserialized parameter data.

The method call can be monitored using tools like Fiddler. The following image shows a method call sent from a SignalR server to a web browser client in the Logs pane of Fiddler. The method call is being sent from a hub calledMoveShapeHub, and the method being invoked is called updateShape.

View of Fiddler log showing SignalR traffic

In this example, the hub name is identified with the H parameter; the method name is identified with the Mparameter, and the data being sent to the method is identified with the A parameter. The application that generated this message is created in the High-Frequency Realtime tutorial.

Choosing a communication model

Most applications should use the Hubs API. The Connections API could be used in the following circumstances:

  • The format of the actual message sent needs to be specified.
  • The developer prefers to work with a messaging and dispatching model rather than a remote invocation model.
  • An existing application that uses a messaging model is being ported to use SignalR.

Reference : http://www.asp.net/signalr/overview/getting-started/introduction-to-signalr

jQuery Templates – XHTML Validation

Maybe you have already tried, and I don’t know what are your results but here is my opinion regarding this.

By default, Visual Studio.NET adds the xhtml1-transitional.dtd schema

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

So, if you try to validate your page which has jQuery Templates against this schema, your page won’t be XHTML valid. Why?

It’s because when creating templates, we use HTML tags inside <script> … </script> block. Yes, I know that the script block has type=”text/html” but it’s not supported in this schema, thus it’s not valid.

Let’s try validate the following code

Code

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml” &gt;
<head>
<title>jQuery Templates :: XHTML Validation</title>
<script src=”http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js” type=”text/javascript”></script&gt;
<script src=”http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js” type=”text/javascript”></script&gt;

<script language=”javascript” type=”text/javascript”>
$(function () {
var attendees = [
{ Name: “Hajan”, Surname: “Selmani”, speaker: true, phones: [070555555, 071888999, 071222333] },
{ Name: “Denis”, Surname: “Manski”, phones: [070555555, 071222333] }
];

$(“#myTemplate”).tmpl(attendees).appendTo(“#attendeesList”);
});
</script>

<script id=”myTemplate” type=”text/html”>
<li>
${Name} ${Surname}
{{if speaker}}
(<font color=”red”>speaks</font>)
{{else}}
(attendee)
{{/if}}
</li>
</script>

</head>
<body>
<ol id=”attendeesList”></ol>
</body>
</html>

To validate it, go to http://validator.w3.org/#validate_by_input and copy paste the code rendered on client-side browser (it’s almost the same, only the template is rendered inside OL so LI tags are created for each item).

Press CHECK and you will get:

Result: 1 Errors, 2 warning(s)

The error message says:

Validation Output: 1 Error

Error Line 21, Column 13: document type does not allow element “li” here

         <li>

Yes, the <li> HTML element is not allowed inside the <script>, so how to make it valid?


1st SOLUTION: Using <![CDATA][…]]>

The first thing that came in my mind was the CDATA. So, by wrapping any HTML tag which is in script blog, inside <![CDATA[ …….. ]]> it will make our code valid. However, the problem is that the template won’t render since the template tags {} cannot get evaluated if they are inside CDATA.

Ok, lets try with another approach.
2nd SOLUTION: HTML5 validation

Well, if we just remove the strikethrough part bellow of the !DOPCTYPE

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&#8221;>

our template is going to be checked as HTML5 and will be valid.

Ok, there is another approach I’ve also tried:
3rd SOLUTION: Separate the template to an external file

We can separate the template to external file. I didn’t show how to do this previously, so here is the example.

1. Add HTML file with name Template.html in your ASPX website.

2. Place your defined template there without <script> tag

Content inside Template.html

<li>
${Name} ${Surname}
{{if speaker}}
(<font color=”red”>speaks</font>)
{{else}}
(attendee)
{{/if}}
</li>

3. Call the HTML file using $.get() jQuery ajax method and render the template with data using $.tmpl() function.

$.get(“/Templates/Template.html”, function (template) {
$.tmpl(template, attendees).appendTo(“#attendeesList”);
});

So the complete code is:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml” &gt;
<head>
<title>jQuery Templates :: XHTML Validation</title>
<script src=”http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js” type=”text/javascript”></script&gt;
<script src=”http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js” type=”text/javascript”></script&gt;

<script language=”javascript” type=”text/javascript”>
$(function () {
var attendees = [
{ Name: “Hajan”, Surname: “Selmani”, speaker: true, phones: [070555555, 071888999, 071222333] },
{ Name: “Denis”, Surname: “Manski”, phones: [070555555, 071222333] }
];

$.get(“/Templates/Template.html”, function (template) {
$.tmpl(template, attendees).appendTo(“#attendeesList”);
});
});
</script>

</head>
<body>
<ol id=”attendeesList”></ol>
</body>
</html>

This document was successfully checked as XHTML 1.0 Transitional!

Result: Passed


UPDATE

SOLUTION 4: Separate the template to an external file and place it inside JavaScript variable

I was pretty sure that someone will mention the <script src=”file-name” /> to load the template. Well, if it’s on the normal HTML-like format we write it, it won’t work

Of course, if you put the template in JS variable and place it in separate JS (or HTML) file, it will work prefectly.

So, we can write the template on the following way:

/Templates/Template.js file

var myTemplate =
“<li>” +
“${Name} ${Surname}” +
“{{if speaker}}” +
“(<font color=\”red\”>speaks</font>)” +
“{{else}}” +
“(attendee)” +
“{{/if}}” +
“</li>”;

So, you can reference this file in your page using <script src=”http://localhost/Templates/Template.js&#8221; type=”text/javascript”></script>

And, to make this work, here is the jQuery code

<script language=”javascript” type=”text/javascript”>
$(function () {
var attendees = [
{ Name: “Hajan”, Surname: “Selmani”, speaker: true, phones: [070555555, 071888999, 071222333] },
{ Name: “Denis”, Surname: “Manski”, phones: [070555555, 071222333] }
];
//myTemplate is the name of the variable
$.template(“myExternalTemplate”, myTemplate); // Compile the template as named template so we can reuse it
$.tmpl(“myExternalTemplate”, attendees).appendTo(“#attendeesList”); //append it to HTML
});
</script>

Instead of using AJAX call, we have replaced this code with the two lines which contains //COMENTS.

This way solves the problem we have. Of course, this is beta version plugin and I do expect in the future to have some functionality to load external templates much easier.

If you have any additional methods for XHTML validation, you can share it :).

 

jQuery Templates with ASP.NET MVC

In my three previous blogs, I’ve shown how to use Templates in your ASPX website.

  1. Introduction to jQuery Templates
  2. jQuery Templates – tmpl(), template() and tmplItem()
  3. jQuery Templates – {Supported Tags}

Now, I will show one real-world example which you may use it in your daily work of developing applications with ASP.NET MVC and jQuery.

In the following example I will use Pubs database so that I will retrieve values from the authors table. To access the data, I’m using Entity Framework.

Let’s pass throughout each step of the scenario:

1. Create new ASP.NET MVC Web application

2. Add new View inside Home folder but do not select a master page, and add Controller for your View

3. BODY code in the HTML

<body>
<div>
<h1>Pubs Authors</h1>
<div id=”authorsList”></div>
</div>
</body>

As you can see  in the body we have only one H1 tag and a div with id authorsList where we will append the data from database.

 

4. Now, I’ve created Pubs model which is connected to the Pub database and I’ve selected only the authors table in my EDMX model. You can use your own database.

5. Next, lets create one method of JsonResult type which will get the data from database and serialize it into JSON string.

public JsonResult GetAuthors()
{
pubsEntities pubs = new pubsEntities();
var authors = pubs.authors.ToList();
return Json(authors, JsonRequestBehavior.AllowGet);
}

So, I’m creating object instance of pubsEntities and get all authors in authors list. Then returning the authors list by serializing it to JSON using Jsonmethod. The JsonRequestBehaviour.AllowGet parameter is used to make the GET requests from the client become allowed. By default in ASP.NET MVC 2 the GET is not allowed because of security issue with JSON hijacking.

 

6. Next, lets create jQuery AJAX function which will call the GetAuthors method. We will use $.getJSON jQuery method.

<script language=”javascript” type=”text/javascript”>
$(function () {
$.getJSON(“GetAuthors”, “”, function (data) {
$(“#authorsTemplate”).tmpl(data).appendTo(“#authorsList”);
});
});
</script>

 

Once the web page is downloaded, the method will be called. The first parameter of $.getJSON() is url string in our case the method name. The second parameter (which in the example is empty string) is the key value pairs that will be send to the server, and the third function is the callback function or the result which is going to be returned from the server.

Inside the callback function we have code that renders data with template which has id #authorsTemplate and appends it to element which has#authorsList ID.

 

7. The jQuery Template

<script id=”authorsTemplate” type=”text/html”>
<div id=”author”>
${au_lname} ${au_fname}
<div id=”address”>${address}, ${city}</div>
<div id=”contractType”>
{{if contract}}
<font color=”green”>Has contract with the publishing house</font>
{{else}}
<font color=”red”>Without contract</font>
{{/if}}
<br />
<em> ${printMessage(state)} </em>
<br />
</div>
</div>
</script>

As you can see, I have tags containing fields (au_lname, au_fname… etc.) that corresponds to the table in the EDMX model which is the same as in the database.

One more thing to note here is that I have printMessage(state) function which is called inside ${ expression/function/field } tag.

The printMessage function

<script language=”javascript” type=”text/javascript”>
function printMessage(s) {
if (s==”CA”) return “The author is from California”;
else return “The author is not from California”;
}
</script>

So, if state is “CA” print “The author is from California” else “The author is not from California”

 

HERE IS THE COMPLETE ASPX CODE

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml” &gt;
<head runat=”server”>
<title>Database Example :: jQuery Templates</title>
<style type=”text/css”>
body
{
font-family:Verdana,Arial,Courier New, Sans-Serif;
color:Black;
padding:2px, 2px, 2px, 2px;
background-color:#FF9640;
}
#author
{
display:block;
float:left;
text-decoration:none;
border:1px solid black;
background-color:White;
padding:20px 20px 20px 20px;
margin-top:2px;
margin-right:2px;
font-family:Verdana;
font-size:12px;
width:200px;
height:70px;}
#address
{
font-style:italic;
color:Blue;
font-size:12px;
font-family:Verdana;
}
.author_hover {background-color:Yellow;}
</style>
<script src=”http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js” type=”text/javascript”></script&gt;
<script src=”http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js” type=”text/javascript”></script&gt;

<script language=”javascript” type=”text/javascript”>
function printMessage(s) {
if (s==”CA”) return “The author is from California”;
else return “The author is not from California”;
}
</script>

<script id=”authorsTemplate” type=”text/html”>
<div id=”author”>
${au_lname} ${au_fname}
<div id=”address”>${address}, ${city}</div>
<div id=”contractType”>
{{if contract}}
<font color=”green”>Has contract with the publishing house</font>
{{else}}
<font color=”red”>Without contract</font>
{{/if}}
<br />
<em> ${printMessage(state)} </em>
<br />
</div>
</div>
</script>
<script language=”javascript” type=”text/javascript”>
$(function () {
$.getJSON(“GetAuthors”, “”, function (data) {
$(“#authorsTemplate”).tmpl(data).appendTo(“#authorsList”);
});
});
</script>
</head>
<body>
<div id=”title”>Pubs Authors</div>
<div id=”authorsList”></div>
</body>
</html>

So, in the complete example you also have the CSS style I’m using to stylize the output of my page.

Here is print screen of the end result displayed on the web page:

You can download the complete source code including examples shown in my previous blog posts about jQuery templates and PPT presentation from my last session I had in the local .NET UG meeting in the following DOWNLOAD LINK.

Do let me know your feedback.

Regards,
Hajan

 

Reducing Code by Using jQuery Templates

Reducing Code by Using jQuery Templates

imageNearly every language out there uses templates in some shape or form to minimize the amount of code that has to be written in an application. By using templates you can define a template structure once and use it to generate code, HTML or other formats. If you’ve created ASP.NET applications then you’re aware of how powerful and productive templates are when it comes to generating HTML output. However, what if you want to use templates on the client-side to generate HTML rather than writing a lot of JavaScript to manipulate the DOM?

Although templates have been available in jQuery for quite awhile through various plug-ins, the latest template framework worked on jointly by Microsoft and the jQuery team provides a great solution that doesn’t use CSS in strange ways or require a lot of knowledge about a template language. By using it you can define HTML templates in web pages and use them to render HTML output dynamically at runtime. I’ll cover the basics of using the jQuery Templates in this post but you can get additional information fromhttp://api.jquery.com/category/plugins/templates.

You can download the jQuery Templates script here along with a sample application or reference one of the following Microsoft CDN scripts:

Defining a Template Block

Templates are defined by referencing the template script mentioned above and then defining a <script> block in your page with a type of text/x-jquery-tmpl as shown next:

 

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

 

Once the script tag is defined you can place template code inside of it. Any HTML that you add is output automatically once the template is rendered. Of course, adding static HTML doesn’t accomplish much so jQuery Templates provides a template tag language that contains several tags that can be placed inside of a template to define data that should be output, perform conditional logic, iterate through items, render nested templates, plus more. The different template tags available with jQuery Templates are are shown next (descriptions and some of the examples are from the jQuery Templates documentation):

Template Tag Example Description
${fieldNameOrExpression} ${ DeliveryFee } Used for insertion of data values in the rendered template. Evaluates the specified field (property) on the current data item, or the specified JavaScript function or expression.
{{html fieldNameOrExpression}} {{html Comments}} Used for insertion of HTML markup strings in the rendered template. Evaluates the specified field on the current data item, or the specified JavaScript function or expression.
{{if}}
{{if DeliveryFee > 0}}
   ${ DeliveryFee } added to your order.
{{/if}}
Used for conditional insertion of content. Renders the content between the opening and closing template tags only if the specified data item field, JavaScript function or expression does not evaluate to false (or to zero, null or undefined).
{{else}}
{{if MainItems.length==0}}
    <tr>
        <td>No items selected</td>
    </tr>
{{else}}
    <tr>
        <td>Ordered items!</td>
    </tr>    
{{/if}}
Used in association with the {{if}}…{{/if}} tag to provide alternative content based on the values of one or more expressions. The {{else}} tag can be used without a parameter, as in: {{if a}}…{{else}}…{{/if}}, or with a parameter, as in: {{if a}}…{{else b}}…{{/if}}.
{{each}}
{{each(i,mi) MainItems}}
    <tr>
        <td>
            ${ mi.NumberOrdered } ordered 
            at $ ${ mi.Price} per item
        </td>
    </tr>
{{/each}}
Used to iterate over a data array, and render the content between the opening and closing template tags once for each data item.
{{tmpl}}
<script id="movieTemplate" type="text/x-jquery-tmpl"> 
    {{tmpl "#titleTemplate"}}
    <tr>
       <td>${ Director }</td>
    </tr>
</script>

<script id="titleTemplate" type="text/x-jquery-tmpl"> 
    <tr>
        <td>${ Name }</td>
    </tr>
</script>
Used for composition of templates. Renders one or more nested template items within the rendered output of the parent template.
{{wrap}}
<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>
Used for composition of templates which incorporate wrapped HTML content. Rendered template items can combine wrapped HTML content with template markup.

 

Rendering a Template

Once a template is defined using a <script> block you can use the jQuery Templates tmpl() function to render the template to a container. This is done by identifying the target template, calling tmpl and passing a JSON object into it and then defining where the rendered output should go:

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

The JSON data can be created locally or retrieved from a remote service call as shown next:

 

$.ajax({
    dataType: 'jsonp',
    url: moviesServiceUrl,
    jsonp: '$callback',
    success: showMovies
});

// Within the callback, use .tmpl() to render the data.
function showMovies(data)
{
    // Render the template with the "movies" data and insert
    // the rendered HTML under the 'movieList' element
    $('#movieTemplate').tmpl(data).appendTo('#movieList');
}

jQuery Templates in Action

A sample application that I created to demonstrate jQuery Templates in action can be downloaded here (it’s part of the sample code available with our jQuery and AJAX Programming training course). The sample app is an ASP.NET MVC 2 project named “Order Up” that leverages jQuery heavily and uses jQuery Templates to render order details. An example of the output that’s rendered is shown next:

image
The template used to generated the Totals, Delivery Information, Items Ordered and Accessories Ordered sections is shown next:

 

<script id="OrderSummaryTemplate" type="text/x-jquery-tmpl">
    <table style="width:100%;">
        <tbody>             
            <tr>
                <td>Totals:</td>                    
            </tr>                    
            <tr>
                <td style="font-size:12pt;">
                    <table style="width:400px;">
                        <tr>
                            <td style="width:50%;">Sub Total:</td>
                            <td>$<span id="FinalSubTotal">${ FinalSubTotal }</span></td>
                        </tr>
                        <tr>
                            <td style="width:50%;">Sales Tax:</td>
                            <td>$<span id="FinalSalesTax">${ FinalSalesTax }</span></td>
                        </tr>
                        {{if DeliveryFee > 0}}
                            <tr>
                                <td style="width:50%;">Delivery Fee:</td>
                                <td>$<span id="FinalDeliveryFee">${ DeliveryFee }</span></td>
                            </tr>
                        {{/if}}
                        <tr>
                            <td style="width:50%;">Admin Fee:</td>
                            <td>$<span id="FinalAdminFee">${ AdminFee }</span></td>
                        </tr>
                        <tr style="border-top:1px solid black;">
                            <td style="width:50%;font-weight:bold;">Total:</td>
                            <td>$<span id="FinalTotal">${ FinalTotal }</span></td>
                        </tr>   
                        <tr>
                            <td colspan="2">&nbsp;</td>
                        </tr>
                        <tr>
                            <td colspan="2">Will be charged to your credit card ending with ${ CreditCard }</td>
                        </tr>                     
                    </table>                        
                </td>
            </tr> 
            <tr>
                <td>&nbsp;</td>
            </tr> 
            <tr>
                <td>Delivery Information</td>                    
            </tr>
            <tr>
                <td>
                    <table style="width:500px;">
                        <tr>
                            <td style="width:25%;">Deliver To:</td>
                            <td>${ DeliveryName }</td>
                        </tr>
                        <tr>
                            <td style="width:25%;">Address:</td>
                            <td>${ DeliveryAddress }</td>
                        </tr>
                        <tr>
                            <td style="width:25%;">Date and Time:</td>
                            <td>${ DeliveryDate } from ${ DeliveryTime }</td>
                        </tr>                        
                    </table>                         
                    </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
            </tr>                    
            <tr>
                <td>Items Ordered</td>
            </tr> 
            {{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}}
            <tr>
                <td>&nbsp;</td>
            </tr>   
            <tr>
                <td>Accessories Ordered</td>
            </tr> 
            {{if AccessoryItems.length==0}}
                <tr>
                    <td>No items selected</td>
                </tr>
            {{else}}
                {{each(i,ai) AccessoryItems}}
                    <tr>
                        <td>
                            ${ ai.Name  } - ${ ai.NumberOrdered } ordered at $ ${ ai.Price } per item
                        </td>
                    </tr>
                {{/each}}
            {{/if}}
            <tr>
                <td>&nbsp;</td>
            </tr>                          
        </tbody>
    </table>    
</script>

The template is rendered to a div with an ID of OrderSummaryOutput using the following code.  The code first creates a JSON object by retrieving data from controls in a checkout wizard and then calls the jQuery Templates tmpl() function:

 

function LoadApprovalDiv()
{
    var subTotal = parseFloat($('#SubTotal').text());
    $('#ClientSubTotal').val(subTotal.toFixed(2));
    var salesTaxRate = parseFloat($('#SalesTaxRate').val()) / 100;
    var salesTaxAmount = (subTotal * salesTaxRate) * .9;
    var deliveryFee = parseFloat($('#DeliveryFee').val());
    var adminFee = ((subTotal + salesTaxAmount + deliveryFee) * .05);
    var total = (Round(subTotal) + Round(salesTaxAmount) + Round(deliveryFee) + 
                 Round(adminFee));
    $('#ClientTotal').val(total);
    var deliveryAddress = $('#Delivery_Street').val();
    //See if they entered a suite
    if ($('#Delivery_Suite').val() != '') deliveryAddress += ', Suite ' + $('#Delivery_Suite').val();
    deliveryAddress += ' ' + $('#Delivery_City').val() + ' ' + $('#Delivery_StateID option:selected').text() + ' ' + 
                       $('#Delivery_Zip').val();
    var creditCard = $('#Payment_CreditCardNumber').val();
    var abbrCreditCard = '*' + creditCard.substring(creditCard.length - 5);

    var json = {
                   'FinalSubTotal'  : subTotal.toFixed(2),
                   'FinalSalesTax'  : salesTaxAmount.toFixed(2),
                   'FinalTotal'     : total.toFixed(2),
                   'DeliveryFee'    : deliveryFee.toFixed(2),
                   'AdminFee'       : adminFee.toFixed(2),
                   'DeliveryName'   : $('#Delivery_Name').val(),
                   'DeliveryAddress': deliveryAddress,
                   'CreditCard'     : abbrCreditCard,
                   'DeliveryDate'   : $('#Delivery_DeliveryDate').val(),
                   'DeliveryTime'   : $('#Delivery_DeliveryTime option:selected').text(),
                   'MainItems'      : GenerateJson('Main'),
                   'AccessoryItems' : GenerateJson('Accessory')
               };

       $('#OrderSummaryOutput').html('');
       //jQuery template example
       $('#OrderSummaryTemplate').tmpl(json).appendTo('#OrderSummaryOutput');

}

If you’re working with 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 normally have to write. It’s a great tool to have in your jQuery arsenal!

 

 

Logo_702D5F60[1]

If you or your company is interested in training, consulting or mentoring on jQuery or .NET technologies please visit http://www.thewahlingroup.com for more information. We’ve provided training, consulting and mentoring services to some of the largest companies in the world and would enjoy sharing our knowledge and real-world lessons learned with you.