Using Mustache.js
Mustache is a template library based on logic-less templates and the JavaScript implementation can be executed on the client side. The basic usage takes two components:
- An HTML template with variables embedded inside double curly braces, e.g. <p>{{myVar}}</p>
- A JSON object with data containing the named object referenced in the template e.g. { “myVar” : “Sting value here” }.
The Mustache.js api provides a method Mustache.to_html()
which compiles the template code with the JSON object to produce a string to insert into the DOM. For example: rendered = Mustache.to_html(view.template, view.model.toJSON());
Simple template used to render a list item
This example will be used by a Backbone View object’s render method which will be used within a CollectionView object with the responsibility of building views from a Backbone collection object
1
|
|
JSON Data: Event object
The data below includes the variables (event_code, sort_order, title) referenced in the the template and other data not utilized in the template.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
Backbone View in a AMD module utilizing Mustache within it’s render() method
The module requires a text/html file by including a string in the dependencies array : 'text!packages/header/templates/event.html'
and assigns the text string to the variable listed in the anonymous function’s arguments named: eventTemplate
. The JSON data is injected when this view constructor is initialized by calling the construction function with the “new” operator and passing in the JSON object as the model data, e.g. "model" : new EventView(model),
The code rendered = Mustache.to_html(view.template, view.model.toJSON());
has a (string) template as the first argument and the second argument is the JSON data object. The result of this to_html
method is assigned to the variable rendered
. Then the view instance’s “render()” method inserts the rendered html into the DOM reference by the Backbone View object’s “el” property… $(view.el).html(rendered);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
Summary
Mustache.js is the template library selected primarily because of the fact that the library is “logic-less” and also is a popular choice since Mustache is implemmented in a wide variety of languages. The fact that no logic is executed in rendering a Mustache template insures that bugs are highly unlikely to be caused due to some logic failing within the operation of executing the template method to render an object as HTML. Logic can be added to the Mustache template within the JavaScript code (e.g. a module for creating a View constructor) which allows for unit testing and debugging utilizing a breakpoint in the code. See the Mustache.js documentation for using conditions, enumerable objects, partials an other Mustache interface functions to for authoring templates with JavaScript, HTML and JSON.