Template engines with ExpressJS


A template engine enables you to use static template files in your application. At runtime, the template engine replaces variables in a template file with actual values, and transforms the template into an HTML file sent to the client. This approach makes it easier to design an HTML page.

Some popular template engines that work with Express are JADE, Mustache, and EJS. The Express application generator uses JADE as its default, but it also supports several others.

To render template files, set the following application setting properties:

  • views, the directory where the template files are located. Eg: app.set('views', './views') This defaults to the views directory in the application root directory.
  • view engine, the template engine to use. For example, to use the JADE template engine: app.set('view engine', 'jade');

Create a JADE template file named index.jade in the views directory, with the following content:

html
  head
    title= title
  body
    h1= message

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

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

When you make a request to the home page, the index.jade file will be rendered as HTML. Jade can be used just as a short hand for HTML.

Jade is designed primarily for server side templating in node.js, however it can be used in many other environments. It is only intended to produce XML like documents (HTML, RSS etc.) so don't use it to create plain text/markdown/CSS/whatever documents.