Expressjs Template Engines


How can we use a particular template engine?

Before Express can render template files, the following application settings have to be set.

  • views: the directory where the template files are located. Eg: app.set('views', './views')
  • view engine: the template engine to use. Eg: app.set('view engine', 'jade')
app.set('views', './views');
app.set('view engine', 'jade');

Once the view engine is set, you don't have to explicitly specify the engine or load the template engine module in your app, Express loads it internally.

How can we make a particular template engine compatible with Express?

Express-compliant template engines such as Jade, export a function named __express(filePath, options, callback), which is called by res.render() to render the template code. Some template engines do not follow this convention, the Consolidate.js library was created to map all of node's popular template engines to follow this convention, thus allowing them to work seamlessly within Express. To better understand how template engines work in Express, read "Developing template engines for Express".

Do we have to specify the view folder and the file extension when using render to render an template?


Create a Jade template files named "index.jade" in the views directory, with the following content.

    title!= title
    h1!= message

Then create a route to render the "index.jade" file. If the view engine property is not set, you will have to specify the extension of the view file, else you can omit it.

app.get('/', function (req, res) {
  res.render('index', { title: 'Hey', message: 'Hello there!'});

On making a request to the home page, "index.jade" will be rendered as HTML.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License