Skip to content

These are the docs of abedmurrar/express, an unofficial fork of Express. The official Express docs are at expressjs.com. What the fork changes is in the Fork section.

Developing template engines for Express ​

Use the app.engine(ext, callback) method to create your own template engine. ext refers to the file extension, and callback is the template engine function, which accepts the following items as parameters: the location of the file, the options object, and the callback function.

The following code is an example of implementing a very simple template engine for rendering .ntl files.

js
const fs = require('fs'); // this engine requires the fs module
app.engine('ntl', (filePath, options, callback) => {
  // define the template engine
  fs.readFile(filePath, (err, content) => {
    if (err) return callback(err);
    // this is an extremely simple template engine
    const rendered = content
      .toString()
      .replace('#title#', `<title>${options.title}</title>`)
      .replace('#message#', `<h1>${options.message}</h1>`);
    return callback(null, rendered);
  });
});
app.set('views', './views'); // specify the views directory
app.set('view engine', 'ntl'); // register the template engine
ts
import fs from 'fs'; // this engine requires the fs module
app.engine(
  'ntl',
  (
    filePath: string,
    options: Record<string, any>,
    callback: (e: any, rendered?: string) => void
  ) => {
    // define the template engine
    fs.readFile(filePath, (err, content) => {
      if (err) return callback(err);
      // this is an extremely simple template engine
      const rendered = content
        .toString()
        .replace('#title#', `<title>${options.title}</title>`)
        .replace('#message#', `<h1>${options.message}</h1>`);
      return callback(null, rendered);
    });
  }
);
app.set('views', './views'); // specify the views directory
app.set('view engine', 'ntl'); // register the template engine

Your app will now be able to render .ntl files. Create a file named index.ntl in the views directory with the following content.

pug
#title#
#message#

Then, create the following route in your app.

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

When you make a request to the home page, index.ntl will be rendered as HTML.

An unofficial fork of Express, not the official project. Code: MIT. Docs adapted from expressjs.com by the Express contributors, CC BY 4.0, with changes (details).