【发布时间】:2022-08-23 20:15:29
【问题描述】:
我在使用 ejs 模板时遇到问题。如果它是一个单一的值,那么它对我来说很好。但是,如果我映射一个数组来呈现多个值,我会收到错误blogs is not defined。这是我的 Node 和 ejs 代码。
应用程序.js
app.get(\'/\', (req, res) => {
const blogs = [
{title: \'Blog1\', text: \'This is blog1.\'},
{title: \'Blog2\', text: \'This is blog2.\'},
{title: \'Blog3\', text: \'This is blog3.\'},
]
res.render(\'index\', {blogs: blogs});
});
索引.ejs
<h3>All Blogs</h3>
<% if(blogs.length > 0) { %> //error: blogs is not defined
<% blogs.forEach(blog => { %>
<h4><%= blog.title %></h4>
<p><%= blog.text %></p>
<% }) %>
<% } else { %>
<p>There are no blogs to display.</p>
<% } %>
标签: javascript node.js express ejs