以下是我server.js
中的内容:
var browserify = require('browserify-middleware');
var express = require('express');
var app = express();
var path = require("path");
app.listen(8080);
console.log('Listening at http://localhost:8080');
// routes will go here
app.get('/render', function(req, res) {
res.sendFile(path.join(__dirname+'/public/index.html'), {text: "sfsdfsf"});
});
以下是我尝试在text
中获取变量index.html
的方法,但是没有效果:
<h1>{{ text }} </h1>
<h1><% text %> </h1>
<script type="text/javascript">
var text = "<%= text %>";
var text2 = "{{ text }}";
</script>
我想出错的任何想法?
答案 0 :(得分:1)
选项1:我建议添加像帕格一样的模板引擎。模板引擎用实际值替换模板文件中的变量。要实施pug模板,请访问https://expressjs.com/en/guide/using-template-engines.html
选项2:
'use strict';
var express = require('express');
var path = require("path");
var app = express();
const template = (text) => {
return `
<!DOCTYPE html>
<html>
<head>
<title>sample</title>
</head>
<body>
<h1>${text}</h1>
</body>
</html>`;
}
app.get('/render', function(req, res) {
res.send(template('Hello'));
});
app.listen(8080);
console.log('Listening at http://localhost:8080');