在EJS中如何使用for循环/for each?

14
我知道它必须放在<% %>里面,但我不确定它是否与典型的forEach/for循环非常不同。EJS网站上的文档非常有限,所以我来这里了。

我知道它必须放在<% %>里面,但我不确定它是否与典型的forEach/for循环非常不同。EJS网站上的文档非常有限,所以我来这里了。

<% 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>

2
请注意,嵌入式js.com网站现在是一个赌场网站。EJS的主要网页已经迁移到这里:https://ejs.co/ - Roly Poly
4个回答

28
这是一个关于嵌入式js的例子。
    <ul>
<% for(var i=0; i<supplies.length; i++) {%>
   <li><%= supplies[i] %></li>
<% } %>
</ul>

这是我做的事情:
<% 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>

22

假设你有一个包含学生姓名、年级和课程等详细信息的学生JSON对象,那么你可以通过forEach循环遍历它,如下所示。

<ul>
 <% students.forEach(function(student) { %>
    <li> Name:<%= student.name %> Course:<%= student.course %></li>
 <% }); %> 
</ul>
同样的方法也适用于您上面提到的作者和引用问题。

0

试一试

 <% 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>

<% }); %>


0
我想使用一个forEach数组方法,并将索引作为第二个参数传递,然后做了这样的事情:
<% 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>
            <% });%> <% }%>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接