我正在构建一个简单的 Web 应用程序,它接受 3 种不同类型的输入并从 View 目录(使用 Node 和 Express)呈现 3 个不同的 EJS 文件之一。每个呈现的 EJS 文件都需要一个静态数组的内容。静态数组很大,我想将它存储在一个单独的 JS 文件中。我尝试将此代码放入 EJS 文件中:
应用程序.js
var arrayFile = require('./arrayFile.js');
app.get("/", async function(req, res){
let blockVariable = await request({
method: "get",
uri: "https://testardor.jelurida.com/nxt?requestType=getBlocks",
json: true
});
var blocks2 = []
blockVariable.blocks.forEach(function(element){
if (element.transactions.length != 0){
blocks2.push(element);
}
});
res.render("home", {blocks: blockVariable.blocks,
blocks2: blocks2,
arrayFile: arrayFile
});
});
首页.ejs
<%= arrayFile %>
数组文件.js
array = [{thing1: 1}, {thing2: 2}]
这会在 home.ejs 页面上给出结果 [object Object]
我尝试制作 home.ejs
<%= JSON.stringify(arrayFile) %>
有结果{}
最佳答案
我认为你在混合上下文。 <script src="arrayFile.js"></script>
将在浏览器端工作。同时 <%= array %>
在服务器端工作。所以它应该是这样的,只是为了给你一个想法:
// assuming that your array is exported as default
var array = require('./arrayFile.js');
app.get('/page', (req, res) => {
// make array available to EJS context
res.render('page_ejs', {array});
});
但这可能会生成一个大的 HTML
带有印记阵列。这可能不是您想要的,因为那样您实际上并不需要 <script src="arrayFile.js"></script>
在你的 EJS 中。
如果您想将文件发送到浏览器,您的 HTML
和 arrayFile.js
,那么您必须在 arrayFile.js
中正确导出数组这样你就可以写这样的东西:
// this will be fetched by browser
<script src="arrayFile.js"></script>
// and then executed by browser
<script>
console.log(yourArray);
</script>
那么你不需要<%= array %>
在你的 EJS 中。
当然,您可以混合使用这两种方式,使数组既可用于 EJS,也可用于浏览器。
关于javascript - 如何从不同的 JS 文件访问 EJS 文件中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53799610/