'can I use partials in a for loop in ejs?
I'm trying to include partials in a for loop in EJS.
<% let index = 1 %>
<% for (let item in db) { %>
<div class="box unfocused box_<%=index %> ">
<% if (db[item].type === "video") { %>
<%- include ('partials/_video.ejs') %>
<% } else if (db[item].type === "collection") { %>
<%- include ('partials/_collection.ejs') %>
<% } else if (db[item].type === "box") { %>
<%- include ('partials/_box.ejs') %>
<% } %>
</div>
<% index ++ %>
<% } %>
For some reason, the variables defined in the for loop are not being passed down into the partial. For example, _video.ejs
looks like this:
<video muted=true autoplay=true loop=true width="250">
<source src="<%=db[item].src%>" type="video/mp4">
</video>
When I run the code, the browser tells me that item
is not defined in _video.ejs
(item
is defined in the for loop).
How to pass item
down into the partial?
Solution 1:[1]
<%for(let post of posts){%>
<%-include('_post',{post: post}); %>
<%}%>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rajesh Behera |