node.jsexpressmustache

Mustache(-like) template engine for Express?


Is there a template engine for Express (node.js) which is based on Mustache or uses a similar syntax?

All I could find is haml, jade, ejs, jquery templates and one based on CoffeeScript (I write plain JS).

I want to write "normal" html, so only ejs and jqtpl would fit. I already use mustache with backbone so it would be best to also use it on the server side with Node.js


Solution

  • You could probably add Mustache as a rendering engine by following the Express manual:

    View filenames take the form “.”, where is the name of the module >that will be required. For example the view layout.ejs will tell the view system to >require(‘ejs’), the module being loaded must export the method exports.compile(str, >options), and return a Function to comply with Express.

    Edit: From the Mustache manual under Usage:

    Below is quick example how to use mustache.js:

    var view = {
      title: "Joe",
      calc: function () {
        return 2 + 4;
      }
    };
    
    var output = Mustache.render("{{title}} spends {{calc}}", view);
    

    In this example, the Mustache.render function takes two parameters: 1) the mustache >template and 2) a view object that contains the data and code needed to render the >template.

    From the above I suspect you could just export Mustache.render, but I haven't tested it. The object literals used as data look the same, but if they do happen to be different, you could probably just wrap Mustache.render in a function that formats it correctly.

    Edit: Xomby's wrapper link contains an example of how to wrap handlebars for express, Mustache should be similar.