Don't like Jade? Use Handlebars instead

I like ExpressJS but i don’t like the Jade template engine. Luckily it’s easy to change the template engine to something awesome like Handlebars!
This is how you use handlebars in Express.

Once you have your Express app up and running, you need to install the awesome view-engine by Eric Ferraiuolo called express3-handlebars

Here’s a step by step guide:

  1. Open up a console and navigation to your Express app folder.

  2. Then install express3-handlebars by typing: npm install express3-handlebars

  3. Then modify your Express app to something like this:

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
34
35
36
/**
* Module dependencies.
*/
var express = require('express');
var exphbs = require('express3-handlebars');
var http = require('http');
var path = require('path');

var app = express();

app.engine('handlebars', exphbs({ defaultLayout: 'main' }));

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'handlebars');

app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}

app.get('/', function(req, res) {
res.render('home');
});

http.createServer(app).listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});

The importants parts being:

exphbs = require('express3-handlebars')

which will load the Handlebars module. And

1
2
app.engine('handlebars', exphbs({ defaultLayout: 'main' }));
app.set('view engine', 'handlebars');

which registers the view engine to be handlebars instead of Jade.

Once this is done you need a few basic Handlebars templates to see it working. You can try these to see it in action:

views/layouts/main.handlebars

1
2
3
4
5
6
7
8
9
10
<!doctype html>  
<html>
<head>
<meta charset="utf-8" />
<title>Example App</title>
</head>
<body>
{{{body}}}
</body>
</html>

views/home.handlebars

1
<h1>Example App: Home</h1>

For further documentation of express3-handlebars take a look the GitHub repo


Comments: