[英]How to loop attributes of an object on EJS?
I am creating sort of an api app with node.js, express, body-parser, ejs, fs.我正在使用 node.js、express、body-parser、ejs、fs 创建一个 api 应用程序。 I have the server running and everything else working.
我的服务器正在运行,其他一切正常。 The problems is that have an object(JSON file) that is parsed, but I can't get access to certain attributes when using my index.ejs template:
问题是有一个被解析的对象(JSON 文件),但是在使用我的 index.ejs 模板时我无法访问某些属性:
{
"x":{
"color": "black"
"total": 1
},
"y":{
"color": "red"
"total": 5
}
}
My javascrip file has the following function that loops trough the file.我的 javascrip 文件具有以下循环通过文件的 function。
var keys = Object.keys(Obj);
for (var i = 0; i< keys.length; i++){
var k = keys[i];
var colorKey = Obj[k].color;
var totalKey = Obj[k].total;
}
var db = keys;
res.render("index", {
db: db
}
Then on my index.ejs I have the code that works with the first attribute ("x" and "y") but can't access the rest.然后在我的 index.ejs 上,我有与第一个属性(“x”和“y”)一起工作的代码,但无法访问 rest。
<% for (var i = 0; i < db.length; i++) { %> ////This is the for loop that shows "x" and "y"
<h1> We have the variable: <%= db[i] %> </h1>
<h1> The color is: <%= db[i].color %></h1>
<h1> There is <%= db[i].total %> left!</h1>
<% } %>
The page shows both variables 's but shows nothing when it comes to color and total.该页面显示了两个变量,但在颜色和总计方面没有显示任何内容。 Is there a way to loop those in ejs?
有没有办法在 ejs 中循环那些?
I presume you don't actually need the preprocessing.我认为您实际上不需要预处理。 Instead, you can do can make an array of keys
相反,你可以做一个键数组
db = /* the source object */
const keys = Object.keys(db)
res.render("index", { db })
<% for (let i = 0; i < keys.length; i++) { %>
<h1> We have the variable: <%= keys[i] %> </h1>
<h1> The color is: <%= db[keys[i]].color %></h1>
<h1> There is <%= db[keys[i]].total %> left!</h1>
<% } %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.