CARVIEW |
Select Language
HTTP/2 200
date: Fri, 18 Jul 2025 01:55:25 GMT
content-type: text/html; charset=utf-8
x-origin-cache: HIT
last-modified: Tue, 15 Jul 2025 18:35:44 GMT
access-control-allow-origin: *
expires: Fri, 18 Jul 2025 01:12:50 GMT
cache-control: max-age=600
x-proxy-cache: MISS
x-github-request-id: 9C88:D1F97:CF746:F6FA8:68799D39
age: 0
via: 1.1 varnish
x-served-by: cache-maa10223-MAA
x-cache: HIT
x-cache-hits: 0
x-timer: S1752803725.924825,VS0,VE225
vary: Accept-Encoding
x-fastly-request-id: 9be4e10253e10e099ec031f47a265e92dc285b74
cf-cache-status: DYNAMIC
server: cloudflare
cf-ray: 960e5b50a9cf1712-BLR
content-encoding: gzip
Developing template engines for Express
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.
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
Your app will now be able to render .ntl
files. Create a file named index.ntl
in the views
directory with the following content.
#title#
#message#
Then, create the following route in your app.
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.