?
This document uses PHP Chinese website manual Release
使用app.engine(ext, callback)
方法創(chuàng)建您自己的模板引擎。ext
指的是文件擴(kuò)展名,并且callback
是模板引擎函數(shù),它接受以下項(xiàng)作為參數(shù):文件的位置,選項(xiàng)對象和回調(diào)函數(shù)。
以下代碼是實(shí)現(xiàn)用于呈現(xiàn).ntl
文件的非常簡單的模板引擎的示例。
var fs = require('fs') // this engine requires the fs module app.engine('ntl', function (filePath, options, callback) { // define the template engine fs.readFile(filePath, function (err, content) { if (err) return callback(err) // this is an extremely simple template engine var 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
您的應(yīng)用現(xiàn)在可以呈現(xiàn).ntl
文件。使用以下內(nèi)容在views
目錄中創(chuàng)建一個名為index.ntl
的文件。
#title# #message#
然后,在您的應(yīng)用程序中創(chuàng)建以下路線。
app.get('/', function (req, res) { res.render('index', { title: 'Hey', message: 'Hello there!' })})
當(dāng)您向主頁發(fā)出請求時,index.ntl
將會呈現(xiàn)為HTML。