Bootcamp
Search…
3.2.1: EJS Loops

Introduction

We can perform JS loops in EJS, for example to create an HTML element for each element in an array.

Example

index.js

app.get('/bananas', (request, response) => {
// data contains an array of elements, each representing 1 user
const data = {
users: [{ name: 'kai' }, { name: 'jim' }, { name: 'susan' }],
};
response.render('index', data);
});

index.ejs

  1. 1.
    Loops run inside EJS tags, and we wrap each conceptual line of JS in its own EJS tags. Notice how the opening and closing lines of the loop are inside separate EJS tags <% %>.
  2. 2.
    The <li> is outside EJS tags. The user.name variable is in a tag that uses the <%= %> tag, where the = denotes variable substitution instead of JS code execution.
<html>
<body>
<ul>
<!-- Create an <li> element for each user in users -->
<% users.forEach((user) => { %>
<li><%= user.name %></li>
<% }); %>
</ul>
</body>
</html>

Further Reading

Read more about the various EJS tags in the Tags section on the EJS website.