Tuesday, 26 February 2019

Express: app.engine(ext, callback): Register template engine


app.engine(ext, callback)
Register template engine for given extensions.

Following code implements custom template engine. If any file ends with extension .ctl, it is handled by this logic.

app.engine('ctl', (filePath, options, callback) => { 

  fs.readFile(filePath, function (err, content) {
    if (err) return callback(err)
  
    var rendered = content.toString().replace('-title-', '<h1> Title: ' + options.title + '</h1>')
    .replace('-message-', '<h1> Message: ' + options.message + '</h1>')
 
 data = "<html><head><title>Demo</title><body>"+rendered+"</body></html>"
 
    return callback(null, data)
  })
  
})

Let’s create views folder and create demoFile.ctl.


demoFile.ctl
-title-
-message-


index.js
const fs = require('fs')
var express = require('express')

var app = express()

app.set('version', '1.2.31')
app.set('maintenanceSupported', true)

app.get('/', (req, res) => {
 res.render('demoFile', { title: 'Hello', message: 'How are you?' })
})

app.set('views', './views') // specify the views directory
app.set('view engine', 'ctl') // register the template engine, ctl : Custom template

const port = 8080;

app.engine('ctl', (filePath, options, callback) => { 

  fs.readFile(filePath, function (err, content) {
    if (err) return callback(err)
  
    var rendered = content.toString().replace('-title-', '<h1> Title: ' + options.title + '</h1>')
    .replace('-message-', '<h1> Message: ' + options.message + '</h1>')
 
 data = "<html><head><title>Demo</title><body>"+rendered+"</body></html>"
 
    return callback(null, data)
  })
  
})

app.listen(3000, () => {console.log("Application started in port 3000")});

Run index.js.


Open the url ‘http://localhost:3000/’ in browser, you can see below content.



Previous                                                 Next                                                 Home

No comments:

Post a Comment