很简单的问题我找不到答案。
使用ExpressJS4.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/development-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.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