EJS while loop
In EJS (Embedded JavaScript), the <% while %>
loop is used to iterate while a certain condition is true. This allows you to generate dynamic content based on repetitive conditions, such as rendering a series of elements until a condition is no longer met.
Syntax and Usage of <% while %>
Loop in EJS
1. Basic Syntax
The basic syntax for a while
loop in EJS is:
<% while (condition) { %> <!-- HTML to render for each iteration --> <% } %>
<% while (condition) { %>
: Starts thewhile
loop. Thecondition
is a JavaScript expression that is evaluated before each iteration.<!-- HTML to render for each iteration -->
: The HTML content that will be rendered repeatedly as long as the condition evaluates totrue
.<% } %>
: Ends thewhile
loop.
2. Example Usage
Server-Side Code (Express):
app.get('/numbers', (req, res) => {
const max = 5; // Define a maximum number
res.render('numbers', { max });
});
EJS Template (views/numbers.ejs
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Number List</title>
</head>
<body>
<h1>Number List</h1>
<ul>
<% let i = 1; while (i <= max) { %>
<li><%= i %></li>
<% i++; %> <!-- Increment i to avoid an infinite loop -->
<% } %>
</ul>
</body>
</html>
In this example:
- The
while
loop iterates from1
tomax
(which is5
). - It generates a list item for each number in the range.
i++
increments the counter to ensure the loop progresses and eventually terminates.
3. Handling Infinite Loops
It's crucial to ensure that the condition of the while
loop will eventually become false
to prevent infinite loops, which can cause your server to hang or crash.
Example of Safe Use:
Server-Side Code:
app.get('/countdown', (req, res) => {
const start = 10; // Countdown starting point
res.render('countdown', { start });
});
EJS Template (views/countdown.ejs
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Countdown</title>
</head>
<body>
<h1>Countdown</h1>
<ul>
<% let count = start; while (count > 0) { %>
<li><%= count %></li>
<% count--; %> <!-- Decrement count to avoid an infinite loop -->
<% } %>
</ul>
</body>
</html>
In this example:
- The
while
loop counts down fromstart
to1
. count--
ensures that the loop eventually terminates whencount
reaches0
.
4. Combining with Other Logic
You can combine while
loops with other control structures and logic to create more complex templates.
Example:
Server-Side Code:
app.get('/sequences', (req, res) => {
const sequences = [
{ start: 1, end: 3 },
{ start: 5, end: 7 }
];
res.render('sequences', { sequences });
});
EJS Template (views/sequences.ejs
):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sequences</title>
</head>
<body>
<h1>Number Sequences</h1>
<% sequences.forEach(seq => { %>
<h2>Sequence from <%= seq.start %> to <%= seq.end %></h2>
<ul>
<% let num = seq.start; while (num <= seq.end) { %>
<li><%= num %></li>
<% num++; %> <!-- Increment to avoid infinite loop -->
<% } %>
</ul>
<% }); %>
</body>
</html>
In this example:
- The
forEach
method is used to iterate over multiple sequences. - Each sequence is processed with a
while
loop to generate numbers fromstart
toend
.
Summary
- Basic Syntax: Use
<% while (condition) { %>
to start the loop and<% } %>
to end it. - Avoiding Infinite Loops: Ensure the condition will eventually become
false
to prevent the loop from running indefinitely. - Combining Logic: Use
while
loops with other control structures for complex data rendering.
The <% while %>
loop in EJS is a versatile tool for creating dynamic content that relies on repetitive conditions, offering flexibility in how you display and manage data on your web pages.