I have an array like so for example:
const arr = ['foo', 'bar', 'baz'];
arr
could have any length, I'm just using this as an example. How would I go about dynamically adding the arr
into a list on ejs.
I'm aware I could do this
// index.ejs
<!doctype html>
<html>
<body>
<ul>
<li><%= item %></li>
</ul>
</body>
</html>
// app.js
res.render('index', {
item: arr[0]
})
Which will render only the first item in the array. How would I make it so it ends up like this:
<html>
<body>
<ul>
<li>foo</li>
<li>bar</li>
<li>baz</li>
</ul>
</body>
</html>
You can use array's forEach
method in ejs the same way you can use it in JavaScript so
<ul>
<% arr.forEach((item) => { %>
<li><%= item %></li>
<% }) %>
</ul>
will solve your problem.
You should probably add test to check whether the arr
actually exists so that it won't try to iterate through it if there is no array (array is undefined
) or its length is zero.
It may happen that you, at some point, send undefined
value for array to view.
res.render('index', { arr: undefined });
In such case, if you don't perform that check, your view will crash because there is no forEach
method of undefined
.
<% if (arr && arr.length) { %>
<ul>
<% arr.forEach((item) => { %>
<li><%= item %></li>
<% }) %>
</ul>
<% } %>
And you need to pass the whole array to the view for the above code to work.
res.render(index, { arr });
Pass the array to the view
// app.js
res.render('index', {
arr
})
Loop through it
<ul>
<% for(var i=0; i<arr.length; i++) {%>
<li><%= arr[i] %></li>
<% } %>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With