Loops and Conditions in EJS Template Files
Make Route and Pass Array in EJS File
In your index.js file (or main Express file), first set up a route that will render your EJS file.
app.get("/users", (req, resp) => {
resp.render("users"); // This will render 'users.ejs' file
});
Note: EJS by default looks inside the views folder, so make sure your EJS file is there.
Create EJS File
Inside the views folder, create a new file called users.ejs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Users List</title>
</head>
<body>
<h1>User List Page</h1>
</body>
</html>
Create an Array and Pass it to EJS
Now go back to your route and pass a list of users to the template.
const users = ["anil", "sidhu", "sam", "peter", "bruce"];
app.get("/users", (req, resp) => {
resp.render("users", { users: users });
});
Here, we are passing the users array to the users.ejs file. You can now use this data inside the template.
Apply Loop in EJS File
Now, inside users.ejs, use a for loop to show each user in a list:
<ul>
<% for (let i = 0; i < users.length; i++) { %>
<li><%= users[i] %></li>
<% } %>
</ul>
- Use
<% %>to write JavaScript (like loops and conditions). - Use
<%= %>to print values to HTML. - Don’t use
=if you’re not printing anything.
Apply Condition in EJS
Let’s say we want to show a message only if the user is logged in. First, create a variable in your route:
app.get("/users", (req, resp) => {
const isLogin = true;
resp.render("users", { users: users, isLogin });
});
Now use this variable in your EJS file with an if condition:
<% if (isLogin) { %>
<h2>User is Logged In</h2>
<% } %>