Tonight I decided to hack on a quick little webapp and use the opportunity to explore some tech that I've only gotten to tinker with so far. I wanted to build a small webapp with express, but I hate jade templating (I realize this may make me a javascript heretic). Since I'd rather just write HTML, I decided to use Mustache (plus, I have previous experience with Mustache).
The biggest problem with Node.js in general is that development is too fast. Blog posts get out of date really quick. I found a few blogs that show how to do it, but they're more than a year old, and at that point, it's almost worthless. Then I found stache. The docs there helped out to get me most of the way there. Here's what I did to get a basic express app using mustache.
First, install express and stache, and then create a new express app named myApp:
sudo npm install -g express stache
express myApp
Now change into the myApp directory. Edit app.js.
var stache = require('stache');
...import stache and then configure the app to use stache (you'll replace the existing jade config)...
app.set('view engine', 'mustache');
app.register('.mustache', stache);
In this case, I'm using a .mustache extension for my templates, and then passing stache to it as the handler for mustache templates.
In your views/ folder, you should see two files that the express command created by default: layout.jade and index.jade. We want to replace these with mustache stubs similar to these files. Let's start with layout.mustache.
<html>
<head>
<title>{{title}}</title>
</head>
<body>
{{{yield}}}
</body>
</html>
In stache, {{{yield}}} seems to be a special keyword for using the subtemplate. Make sure you remember all three suspenders around it, or you'll spend 20 minutes scratching your head and wondering why the HTML is being escaped (a behavior I hadn't ever used in mustache).
Now in index.mustache, we add the following:
<h1>{{title}}</h1>
<p>Welcome to {{title}}</p>
At this point, we've got a similar layout and template to the jade templates. The last thing left to do is change the data structure of the context we pass (since mustache wants the template context in a different format). Crack open routes/index.js and change the res.render call to look like this:
res.render('index', {
locals: {
title: 'Express'
}
});
Now fire up the app with node app.js and hit /. Does everything work? Hooray! If not, uh, sorry. I'd be interested to know what didn't work, so I can fix the post.
In fact, since Node.js posts tend to get out of date, if this one does, please let me know and I'll update it accordingly.