使用 app.engine(ext, callback)
方法建立自己的範本引擎。ext
指的是檔案副檔名,而 callback
是範本引擎函式,它接受下列項目作為參數:檔案位置、選項物件和回呼函式。
以下程式碼是實作一個非常簡單的範本引擎來呈現 .ntl
檔案的範例。
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
您的應用程式現在可以呈現 .ntl
檔案。在 views
目錄中建立一個名為 index.ntl
的檔案,並輸入以下內容。
#title#
#message#
然後,在您的應用程式中建立以下路由。
app.get('/', (req, res) => {
res.render('index', { title: 'Hey', message: 'Hello there!' })
})
當您對首頁提出要求時,index.ntl
將會以 HTML 呈現。