14

I know it has to go inside <% %>, but I'm not sure if it's very different from a typical forEach/for loop. The documentation on the EJS site is pretty limited, so I came here.

<% include ../../partials/header %>

<body>
  <main>
    <h1>List of all quotes</h1>
    <ul>
      <li> <!-- for loop goes here, inside flounder -->
        <%
        all quote stuff goes here
        author
        content
        wrap it in a link to its quote page
      </li>
    </ul>
  </main>
</body>

</html>
Tsardines
  • 883
  • 2
  • 8
  • 17

4 Answers4

28

So here's the example on embeddedjs:

    <ul>
<% for(var i=0; i<supplies.length; i++) {%>
   <li><%= supplies[i] %></li>
<% } %>
</ul>

And here's what I did:

<% include ../../partials/header %> <
<body>
  <main>
    <h1>List of all quotes</h1>
    <ul>
      <% for(var i = 0; i < author.length; i++) { %>
        <li><%= author[i] %></li>
      <% } %>

      <% for(var i = 0; i < content.length; i++) { %>
        <li><%= content[i] %></li>
      <% } %>

    </ul>
  </main>
</body>

</html>
Community
  • 1
  • 1
Tsardines
  • 883
  • 2
  • 8
  • 17
22

Let say you have a student JSON object with details of student name, year and course then you can loop through with forEach as follows.

<ul>
 <% students.forEach(function(student) { %>
    <li> Name:<%= student.name %> Course:<%= student.course %></li>
 <% }); %> 
</ul>

The same can apply for your author and quote question above

Jack Crispy
  • 105
  • 2
  • 11
Kipruto
  • 721
  • 6
  • 16
0

I wanted to use a forEach array method and pass the index as a second parameter and did something like this:

<% orders.products.forEach((order,index) => {%>
            <tr>
              <td><%= index+1 %></td>
              <td><%= order.description %></td>
              <td><%= order.price %></td>
              <td><%=order.quantity %></td>
              <td><%=orders.amount %></td>
              <td><%=order.salesTax %></td>
              <td><%=order.tax %></td>
              <td><%=order.amount %></td>
            </tr>
            <% });%> <% }%>
Blessing
  • 2,450
  • 15
  • 22
0

Try This

 <% users.forEach(function(user, i){ %>
<tr>
    <th scope="row"> <%= i+1 %> </th>
    <td><%= user.name %></td>
    <td><%= user.email %></td>
    <td><%= user.gender %></td>
    <td><%= user.status %></td>
    
</tr>

<% }); %>

IslamYearul
  • 318
  • 3
  • 10