Express 自定义模板引擎

使用"app.engine(ext,callback)"方法,可以创建自定义的模板引擎."ext"是模板文件的扩展名,"callback"是模板引擎方法,参数为本地文件路径,选项对象,和一个回调函数.

下面是一个非常简单的模板引擎实现,用于渲染后缀为".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(new Error(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

 现在你的程序能渲染后缀为".ntl"的文件了.在模板文件夹中创建一个名为"index.ntl"文件,内容如下:

#title#
#message#

 然后,创建如下路由:

app.get('/', function (req, res) {
  res.render('index', { title: 'Hey', message: 'Hello there!'});
})

 现在,访问首页,"index.ntl"文件将被渲染为html文件显示.

猜你喜欢

转载自zy-email1991.iteye.com/blog/2195487