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.
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.
Create an Array and Pass it to EJS
Now go back to your route and pass a list of users to the template.
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:
- 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:
Now use this variable in your EJS file with an if condition: