EJS foreach loop
In EJS (Embedded JavaScript), the forEach
method is used to iterate over arrays or collections, allowing you to dynamically generate HTML based on each item in the array. It provides a convenient way to work with array elements in your templates without needing to manually manage loop counters.
Syntax and Usage of forEach
in EJS
1. Basic Syntax
The forEach
method in EJS is used as follows:
<% array.forEach(item => { %> <!-- HTML to render for each item --> <% }); %>
<% array.forEach(item => { %>
: Starts theforEach
loop.array
is the array you're iterating over, anditem
represents the current element in each iteration.<!-- HTML to render for each item -->
: This is the content rendered for each item in the array.<% }); %>
: Ends theforEach
loop.
2. Example Usage
Server-Side Code (Express):
app.get('/fruits', (req, res) => {
const fruits = ['Apple', 'Banana', 'Cherry'];
res.render('fruits', { fruits });
});
EJS Template (views/fruits.ejs
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fruits List</title>
</head>
<body>
<h1>Fruits List</h1>
<ul>
<% fruits.forEach(fruit => { %>
<li><%= fruit %></li>
<% }); %>
</ul>
</body>
</html>
In this example:
- The
forEach
loop iterates over thefruits
array. - Each
fruit
in the array is displayed as a list item (<li>
).
3. Using Indexes
If you need the index of the current element in addition to the element itself, you can use the second parameter of forEach
:
Example:
Server-Side Code:
app.get('/students', (req, res) => {
const students = [
{ name: 'Alice', age: 20 },
{ name: 'Bob', age: 22 },
{ name: 'Charlie', age: 23 }
];
res.render('students', { students });
});
EJS Template (views/students.ejs
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Students List</title>
</head>
<body>
<h1>Students List</h1>
<ul>
<% students.forEach((student, index) => { %>
<li>Student <%= index + 1 %>: <%= student.name %>, Age: <%= student.age %></li>
<% }); %>
</ul>
</body>
</html>
In this example:
- The
forEach
method iterates over thestudents
array. - Both the
student
object and theindex
of the current iteration are used to display information.
4. Combining with Conditional Logic
You can combine forEach
with conditional statements to create more complex templates:
Example:
Server-Side Code
app.get('/tasks', (req, res) => {
const tasks = [
{ title: 'Buy groceries', completed: true },
{ title: 'Clean the house', completed: false },
{ title: 'Finish homework', completed: true }
];
res.render('tasks', { tasks });
});
EJS Template (views/tasks.ejs
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tasks List</title>
</head>
<body>
<h1>Tasks List</h1>
<ul>
<% tasks.forEach(task => { %>
<li>
<%= task.title %>
<% if (task.completed) { %>
<span style="color: green;">(Completed)</span>
<% } else { %>
<span style="color: red;">(Pending)</span>
<% } %>
</li>
<% }); %>
</ul>
</body>
</html>
In this example:
- The
forEach
method iterates over thetasks
array. - Conditional logic is used to display different status messages based on whether the task is completed or not.
Summary
- Basic Syntax: Use
<% array.forEach(item => { %>
to iterate over an array, and<% }); %>
to end the loop. - Index Usage: Access the index of the current item with the second parameter in
forEach
. - Conditional Logic: Combine
forEach
with conditional statements to render complex content.
The forEach
loop in EJS simplifies the process of iterating over arrays and collections, making it easier to generate repetitive or dynamic content in your templates.