Vertebrae framework

built with Backbone.js and RequireJS using AMD

Backbone Views Using Mustache Templates

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:

  1. An HTML template with variables embedded inside double curly braces, e.g. <p>{{myVar}}</p>
  2. 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

(event.html) download
1
<a href="/event/{{event_code}}" data-sort="{{sort_order}}">{{title}}</a>

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.

(event-object.json) download
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
{
    "event_id": "12366",
    "event_code": "12366stellaandjamiewc",
    "start_date": "2011-12-28T08:00:00-08:00",
    "end_date": "2011-12-30T08:00:00-08:00",
    "image_url": "/assets/12366stellaandjamiewc/event-small.jpg",
    "info": "/assets/12366stellaandjamiewc/info.txt",
    "video": "/assets/12366stellaandjamiewc/video.mp4",
    "title": "Stella & jamie",
    "tagline": "Sequins and detailing that dress things up",
    "event_types": [
        {
            "name": "Women"
        }
    ],
    "meta": {
        "msa": [],
        "status": "Active",
        "private_event": false,
        "exclusive": false,
        "preview": false,
        "nested": {
            "parents": [],
            "children": [],
            "siblings": []
        }
    },
    "description": "Sequins and detailing that dress things up.",
    "coa": "womens_apparel",
    "sort_order": "2",
    "category": "Accessories",
    "event_display_format": "Regular"
}

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);

(event.js) download
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
// event view 
// ----------
// @requires define

define(['jquery',
        'underscore',
        'backbone',
        'views/base',
        'text!packages/header/templates/event.html',
        'mustache',
        'utils/debug'],
function ($, _, Backbone, BaseView, eventTemplate, Mustache, debug) {

    var EventView;

    EventView = BaseView.extend({

        initialize: function () {
            this.template = eventTemplate;
            debug.log('EventView init');
        },
        render: function () {
            var view = this, rendered;

            rendered = Mustache.to_html(view.template, view.model.toJSON());
            $(view.el).html(rendered);
            debug.log('EventView rendered');
            return view;
        }
    });

    return EventView;
});

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.