ExpressJS 4.x:仅使用变量渲染index.html例如在Django中

问题描述

非常简单的问题,我找不到答案。

我想使用Expressjs 4.x:

app.get('/',function(req,res) {
    res.render('index.html',{name:"Peter"});
});

然后我的index.html我希望它像:

<!DOCTYPE html>
<html>
  <body>
     <h1>Hello {{ name }}</h1>
  </body>
</html>

我想编写纯HTML (没有伪像pug,ejs等的伪html),只是纯html,并以这种方式添加了变量:{{variable}}

有可能吗?必须很容易...

非常感谢您的帮助!

解决方法

http://expressjs.com/en/advanced/developing-template-engines.html修改而来。

基本上使用正则表达式将{{。*}}与替换函数匹配,以将{{}}转换为视图数据中的值。

var fs = require('fs'); // this engine requires the fs module
app.engine('html',function (filePath,options,callback) { // define the template engine
  fs.readFile(filePath,function (err,content) {
    if (err) return callback(new Error(err));
    
    var rendered = content.toString().replace(/{{([^}]+)}}/g,function(match,p1) {
      return options[p1.trim()];
    });

    return callback(null,rendered);
  });
});
app.set('views','./views'); // specify the views directory
app.set('view engine','html'); // register the template engine