正如标题中所提到的,当在html模板中引用数据时,它是未定义的。
JS:
var data = [];
for (var i = 0; i < rows.length; i++) {
data.push(rows[i]);
if (i == rows.length - 1) {
fs.readFile('tree.html', 'utf8', function (err, html) {
console.log(data);
var template = _.template(html);
var result = template({ data: data });
res.send(result);
});
}
}
HTML:
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<title></title>
</head>
<body>
<%
console.log(data);
%>
</body>
</html>
答案 0 :(得分:1)
我是新的强调,但它对我来说很好。检查你错过了什么。
文件结构:
--test.html
--test.js
的test.html
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<title></title>
</head>
<body>
<%
console.log(data, 'it works! ');
%>
</body>
</html>
test.js
var data = [], rows = [1,2,3,4];
var _ = require('underscore'),
fs = require('fs');
for (var i = 0; i < rows.length; i++) {
data.push(rows[i]);
if (i == rows.length - 1) {
fs.readFile('test.html', 'utf8', function(err, html) {
console.log(html); // correct html file content
var template = _.template(html);
var result = template({
data: data // After console print the html file,
// it runs the script code in html file,
// which in my point of view, means `template` works.
});
// res.send(result);
});
}
}
在终端中运行node test.js
,它运行正常。
PS:我做了console.log(result)
并得到了正确的结果:
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<title></title>
</head>
<body>
</body>
</html>