new*_*bie 4 javascript ejs node.js
我有一个像这样的数组,例如:
const arr = ['foo', 'bar', 'baz'];
arr可以有任何长度,我只是用这个作为例子。我将如何动态地将其添加arr到 ejs 上的列表中。
我知道我可以做到这一点
// index.ejs
<!doctype html>
<html>
<body>
<ul>
<li><%= item %></li>
</ul>
</body>
</html>
// app.js
res.render('index', {
item: arr[0]
})
Run Code Online (Sandbox Code Playgroud)
这将仅渲染数组中的第一项。我将如何做到它最终会像这样:
<html>
<body>
<ul>
<li>foo</li>
<li>bar</li>
<li>baz</li>
</ul>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
您可以在 ejs 中使用数组的forEach方法,就像在 JavaScript 中使用它一样
<ul>
<% arr.forEach((item) => { %>
<li><%= item %></li>
<% }) %>
</ul>
Run Code Online (Sandbox Code Playgroud)
会解决你的问题。
您可能应该添加测试来检查是否arr实际存在,这样如果没有数组(数组是undefined)或其长度为零,它就不会尝试迭代它。您可能会在某个时刻发送undefined数组值以供查看。
res.render('index', { arr: undefined });
Run Code Online (Sandbox Code Playgroud)
在这种情况下,如果您不执行该检查,您的视图将崩溃,因为forEach没有undefined.
<% if (arr && arr.length) { %>
<ul>
<% arr.forEach((item) => { %>
<li><%= item %></li>
<% }) %>
</ul>
<% } %>
Run Code Online (Sandbox Code Playgroud)
并且您需要将整个数组传递给视图才能使上述代码正常工作。
res.render(index, { arr });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3983 次 |
| 最近记录: |