ExpressJS 4.x:简单地使用变量渲染 index.html(就像在 Django 中一样)
ExpressJS 4.x: simply render index.html with variables (like in 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>
我想写 plain 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
非常简单的问题我找不到答案。
使用 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>
我想写 plain 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