Bootcamp
Search…
3.2.2: EJS Conditionals

Introduction

Similar to 3.2.1: EJS Loops, we can inject conditional statements into EJS using the same <% %> syntax. Typically we perform data calculation logic in request handlers and use as little JS logic in EJS as possible. This is to keep our app organised by separating logic and UI concerns as far as possible.

index.js

We assume the following route in index.js that sends user data to user-data.ejs.
app.get('/user-data', (request, response) => {
const data = {
users: [{ name: 'kai' }, { name: 'jim' }, { name: 'susan' }],
};
response.render('user-data', data);
});

user-data.ejs

Render a special message if there are more than 100 users. Notice there is no EJS templating around the HTML within the conditional statement.
<html>
<body>
<!-- Only show this message if there are over 100 users. -->
<% if (users.length > 100) { %>
<h1>Wow, you have a lot of users!</h1>
<% } %>
<!-- Render all user names -->
<ul>
<% users.forEach((user) => { %>
<li><%= user.name %></li>
<% }); %>
</ul>
</body>
</html>
Copy link