🌐 Nodejs.cn

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