This is a short guide on configuring EmbeddedJS (EJS) with the Express 3 framework for Node.js. Many of the online tutorials deal with configuration for Express 2. Express 3 does things a bit differently. I'll show you how to get templating/layouts working with Express 3.
The main thrust of changes are covered in the Migrating Guide for Express. In particular, under the "View systems changes" you'll see that Express 3 no longer supports integrated layout processing. This is deferred to the view engine.
In this case, we'll use ejs-locals to provide layout and partial templating support in addition to ejs.
Assuming you have already created your express application. You will now need to add ejs and ejs-locals.
node install ejs
node install ejs-locals
Now you just need to set up you app.
/app.js
var express = require('express')
, app = express()
, engine = require('ejs-locals');
// specify the ejs engine should use the ejs-locals wrapper for ejs
app.engine('ejs', engine);
// set the view engine to ejs
app.set('view engine', 'ejs');
// specify the views root path
app.set('views', __dirname + '/views');
This code follows boilerplate for creating a new express app. We create a new reference to ejs-locals
and configure Express to use ejs-locals
when rendering anything using EJS with the app.engine('ejs', engine)
statement. More info about app.engine.
/views/layout.ejs
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
</head>
<body>
<%- body %>
</body>
</html>
[/code]
/views/index.ejs
[code lang="html"]
<% layout('layout') %>
<h1>I am inside the layout</h1>
Finally, in our views, we can simply call the layout of our choosing.