Wednesday, December 11, 2013

Tutorial: HTML Templates with Mustache.js

When developing modern HTML applications, you often write a lot of HTML fragments programmatically. You concatenate HTML tags and dynamic data, and insert the resulting UI markup into the DOM. Here is a random code example of this approach:

1

2

3

4

5

6

7

8

9

$.each(messages.reverse(), function(index, message) {

$('#messageList').append(

'

'

+

message.userName + '

' +

'+

message.datePosted + '">

' +

'

'

+ message.messageText + '

');

}

});

The proliferation of this kind of code throughout your application comes with some downsides. The tight coupling of UI and data logic doesn’t promote separation of concerns and reuse. It makes your application harder to write and harder to maintain.HTML templates address this issue by decoupling the UI definition (HTML markup) from the data. There are a number of HTML template solutions out there: jQuery Templates, Underscore.js, and Mustache.js to name a few. Mustache.js is a popular choice because of its powerful syntax and fast rendering.

Lisa Jones

NOTE: Sample 3 represents the way templates are being used in many dynamic Web applications:

You get data from an Ajax service

You read the template from an external file

In the remaining of this article, we declare the data and the template in variables to keep the examples self-contained. Remember to refer to sample 3 for a traditional setup when using templates in a dynamic Web application.

Sample 9: Condition

Templates can include conditional sections. Conditional sections only render if the condition evaluates to true. A conditional section begins with {{#condition}} and ends with {{/condition}}. “condition” can be a boolean value or a function returning a boolean.