The first step in implementing a template engine is to define a default template engine for the Express application. You do this by setting the view engine
setting on the express()
application object. You also need to set the views
setting to the location where your template files will be stored. For example, the following sets the ./views
directory as the root for template documents and jade
as the view engine:
var app = express();
app.set('views', './views'),
app.set('view engine', 'jade'),
Then you need to register the template engines for the template extensions that you want them to handle by using the app.engine(ext, callback)
method. The ext
parameter is the file extension used for the template files, and the callback
parameter is a function that supports Express’s rendering functionality.
Many engines provide the callback functionality in an __express
function. For example:
app.engine('jade', require('jade').__express)
The __express
functionality often only works on the default filename extension. In that case, you can use a different function. For example, EJS provides the renderFile
function for that purpose. You can use the following to register EJS for ejs
extensions:
app.engine('ejs', require('ejs').__express)
However, if you want to register EJS for HTML extensions, you need to use:
app.engine('html', require('ejs').renderFile)
Once the extension is registered, the engine callback function is called to render any templates with that extension. If you choose a different engine besides Jade or EJS, you need to figure out how they expect to register with Express.