Using Mustache Templates in Express

I was a little surprised to find that Express doesn’t offer support for Mustache out of the box (or even through any third party libs). But after looking at #donpark's hbs bridge for Handlebars, I realized why: it’s almost not enough code to warrant its own library (might be nice to include directly in Express though).

In any case, for those of you who may be interested in using Mustache with Express, here’s a simplified example demonstrating the code I’m using to bridge the two (borrowed heavily from hbs):

var express = require("express");
var mustache = require("./mustache.js");

var tmpl = {
    compile: function (source, options) {
        if (typeof source == 'string') {
            return function(options) {
                options.locals = options.locals || {};
                options.partials = options.partials || {};
                if (options.body) // for express.js > v1.0
                    locals.body = options.body;
                return mustache.to_html(
                    source, options.locals, options.partials);
            };
        } else {
            return source;
        }
    },
    render: function (template, options) {
        template = this.compile(template, options);
        return template(options);
    }
};

var app = express.createServer();

app.configure(function() {
    app.use(express.methodOverride());
    app.use(express.bodyDecoder());
    app.use(app.router);
    app.set("views", __dirname);
    app.set("view options", {layout: false});
    app.register(".html", tmpl);
    app.use(express.errorHandler({
        dumpExceptions:true, 
        showStack:true
    }));
});

app.get("/", function(req, res) {
    res.render("index.html", {
        locals: {
            message: "Hello World!",
            items: ["one", "two", "three"]
        },
        partials: {
            foo: "<h1>{{message}}</h1>",
            bar: "<ul>{{#items}}<li>{{.}}</li>{{/items}}</ul>"
        }
    });
});

app.listen(3001);

And here’s the example index.html file:

<html>
    <head>
        <title>{{message}}</title>
    </head>
    <body>
        {{>foo}}
        {{>bar}}
    </body>
</html>

You also need to change the first line of mustache.js from:

var Mustache = function() {

to:

var Mustache = module.exports = function() {

or you won’t be able to import in node.js.

Initially I was hoping to use Handlebars instead, but after running into several show-stopping bugs, I was forced back to Mustache. I’ll have to give it another shot in a few months.

In either case, it sure beats ejs (which I had been using). My templates are looking mighty clean now!

Oh, and If you like coding with mustaches, try the strangely named ICanHaz.js as well. Very satisfying.