gpt4 book ai didi

javascript - 传递到下划线模板的数据未定义

转载 作者:行者123 更新时间:2023-12-03 07:02:51 24 4
gpt4 key购买 nike

正如标题中提到的,当在 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>

最佳答案

我是下划线新手,但它对我来说效果很好。检查一下你错过了什么。

文件结构:

--test.html
--test.js

测试.html

<html xmlns="http://www.w3.org/1999/xhtml"><head>
<title></title>
</head>
<body>
<%
console.log(data, 'it works! ');
%>
</body>
</html>

测试.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,它工作正常。

enter image description here

PS:我做了console.log(result)并得到了正确的结果:

<html xmlns="http://www.w3.org/1999/xhtml"><head>
<title></title>
</head>
<body>

</body>
</html>

关于javascript - 传递到下划线模板的数据未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36957983/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com