为 Express 开发模板引擎

¥Developing template engines for Express

使用 app.engine(ext, callback) 方法创建你自己的模板引擎。ext 指的是文件扩展名,callback 是模板引擎函数,它接受以下几项作为参数:文件的位置、选项对象和回调函数。

¥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.

下面的代码是实现一个非常简单的用于渲染 .ntl 文件的模板引擎的示例。

¥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

你的应用现在将能够渲染 .ntl 个文件。使用以下内容在 views 目录中创建名为 index.ntl 的文件。

¥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!' })
})

当你向主页发出请求时,index.ntl 将渲染为 HTML。

¥When you make a request to the home page, index.ntl will be rendered as HTML.