Integrate a custom engine
A rendering package does not expose Express's expected integration property.
Express.js · Module
Registers a template-engine callback for a file extension. Use it for custom engines or to map an alternate extension to an engine.
app.engine registers a rendering callback for a file extension. The callback receives the view file path, rendering options, and a completion callback; it must return either an error or rendered output, after which Express can use the engine for matching views.
app.engine(ext, callback)| Name | Type | Description |
|---|---|---|
ext | String | File extension for which the template engine is registered, such as pug or html. |
callback | Function | Template-engine function used to render files with the specified extension. |
Application
const express = require('express');
const fs = require('fs');
const app = express();
app.engine('ntl', (filePath, options, callback) => {
fs.readFile(filePath, (err, content) => {
if (err) return callback(err);
const rendered = content.toString()
.replace('#title#', `<title>${options.title}</title>`)
.replace('#message#', `<h1>${options.message}</h1>`);
callback(null, rendered);
});
});
app.set('views', './views');
app.set('view engine', 'ntl');
app.get('/', (req, res) => res.render('index', { title: 'Home', message: 'Hello' }));
app.listen(3000);Registers a minimal file-based .ntl engine, configures it as the view engine, and renders a view.
A rendering package does not expose Express's expected integration property.
Templates use a file suffix different from the engine's default suffix.
An application needs a small project-specific renderer.
app.engine(ext, callback) registers the callback as the renderer for the supplied extension and returns the application object. The extension identifies the view files handled by that renderer.
Follow-up: How would you support an engine under a different extension? Register the desired extension with app.engine and provide the engine's rendering callback.
The callback is the template-engine function used to render files with the registered extension. A custom callback convention receives the file location, options object, and completion callback, then reports an error or rendered text.
Follow-up: What should the completion callback receive on success? It should receive no error and the rendered output.
Express normally loads a template engine according to the view file extension. app.engine is appropriate when the engine does not provide __express or when an extension must be mapped to another engine.
Follow-up: What other settings are needed for a complete custom-engine setup? Configure the views directory and set the view engine extension before rendering views.
app.setapp.renderres.renderview engineviews