Use the 使用app.engine(ext, callback)
method to create your own template engine. app.engine(ext, callback)
方法创建自己的模板引擎。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.ext
是指文件扩展名,callback
是模板引擎函数,它接受以下项作为参数:文件的位置、选项对象和回调函数。
The following code is an example of implementing a very simple template engine for rendering 下面的代码是实现用于呈现.ntl
files..ntl
文件的非常简单的模板引擎的示例。
var fs = require('fs') // 此引擎需要fs模块
app.engine('ntl', function (filePath, options, callback) { // 定义模板引擎
fs.readFile(filePath, function (err, content) {
if (err) return callback(err)
// 这是一个非常简单的模板引擎
var rendered = content.toString()
.replace('#title#', '<title>' + options.title + '</title>')
.replace('#message#', '<h1>' + options.message + '</h1>')
return callback(null, rendered)
})
})
app.set('views', './views') // 指定视图目录
app.set('view engine', 'ntl') // 注册模板引擎
Your app will now be able to render 您的应用程序现在将能够呈现.ntl
files. .ntl
文件。Create a file named 在视图目录中创建一个名为index.ntl
in the views
directory with the following content.index.ntl
的文件,其中包含以下内容。
#title#
#message#
Then, create the following route in your app.然后,在应用程序中创建以下路由。
app.get('/', function (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.index.ntl
将呈现为HTML。