Developing template engines for Express为Express开发模板引擎
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.app.engine(ext, callback)
方法创建自己的模板引擎。ext
是指文件扩展名,callback
是模板引擎函数,它接受以下项目作为参数:文件的位置、选项对象和回调函数。
The following code is an example of implementing a very simple template engine for rendering 以下代码是实现用于呈现.ntl
files..ntl
文件的非常简单的模板引擎的示例。
const fs = require('fs') // this engine requires the fs module此引擎需要fs模块
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
Your app will now be able to render 您的应用程序现在将能够渲染.ntl
files. Create a file named index.ntl
in the views
directory with the following content..ntl
文件。在views
目录中创建一个名为index.ntl
的文件,其中包含以下内容。
#title#
#message#
Then, create the following route in your app.然后,在您的应用程序中创建以下路线。
app.get('/', (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。