Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 968
Xomby Avatar asked Nov 30 '22 06:11

Xomby


2 Answers

Just stumbled on this ancient thread but no one has mentioned consolidate.js, which seems to be the "right" way under Express 3 (refer to http://expressjs.com/faq.html). It also provides an easy way to switch/experiment with templating systems.

Here's a simple example - http://invitingthebell.com/2012/12/24/mustache-templates-in-express-3-0/.

Code, in case it disappears is:

var express = require('express')
 , cons = require('consolidate')
 , app = express();

// assign the mustache engine to .html files
app.engine('html', cons.mustache);

// set .html as the default extension 
app.set('view engine', 'html');

app.set('views', __dirname + '/views');

// test mustache
app.get('/', function(req, res){ 
  var viewdata = { 'test' : 'Hey now.'};
  res.render('index', viewdata);
});

app.listen(3000);

The index.html file in the views directory:

<html>
  <head><title>Some CMS</title></head>
  <body>
    <h1>Mustache</h1>
    <p>What do you say?</p>
    <p>{{test}}</p>
  </body>
</html>
like image 136
Sean Chou Avatar answered Dec 05 '22 14:12

Sean Chou


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.

like image 24
mtsr Avatar answered Dec 05 '22 13:12

mtsr