July 17, 2024

ExpressJS: EJS Template Iteration Examples

In the post ExpressJS: EJS Template Engine Integration With Examples we have seen how you can use EJS template with Express.js app. In this post we'll see how to iterate over an array or object in EJS template.

Iteration in EJS

EJS template uses JavaScript code with in the scriptlet tags <% %>. Which means you can use the same loops which are used in JavaScript to iterate an array or object in EJS.

Loops that can be used are-

  1. Normal for loop
  2. While loop
  3. for-of to iterate array
  4. forEach to loop array
  5. for-in to iterate an object

Express.js - EJS iteration example

Let's assume we have an array of User objects which we want to iterate and display in our view named 'user.ejs' which is created as a EJS template.

app.js

const express = require('express');

const app = express();

const port = 3000;
const path = require('path');

// To serve static files like CSS
app.use(express.static(path.join(__dirname, 'public')));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// Hardcoded user data
const users = [{name:'Reene', age: 28, gender:'F'}, 
    {name:'Badal', age: 34, gender:'M'},
    {name:'Vidyut', age: 25, gender:'M'},
    {name:'Dhriti', age: 29, gender:'F'}
]

app.get('/user', (req, res) => {
    res.render('user', {users: users, pageTitle: 'User Page'});
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

As you can see in the code there is an array named users that contains user objects. There is also a mapping '/user' which renders the user.ejs template and values for variables users and pageTitle in the view are also passed.

public\css\user.css

CSS used for styling table.

table, td, th {
  border: 1px solid;
}
table {
  width: 80%;
  border-collapse: collapse;
}

views\user.ejs

<!DOCTYPE html>
<html lang="en">
  <head>
    <title><%= pageTitle%></title>
    <link rel="stylesheet" href="/css/user.css">
  </head>
  <body> 
    <h2>Using while loop</h2>
    <table>
      <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Gender</th>
      </tr>
      <% 
      let i = 0;
      while(i < users.length) {%>
      <tr> 
        <td><%= users[i].name%></td>
        <td><%= users[i].age%></td>
        <td><%= users[i].gender%></td>
      </tr>
      <% i++;
      }%>
    </table>
    <h2>Using normal for loop</h2>
    <table>
      <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Gender</th>
      </tr>
      <% for(let i= 0; i < users.length; i++) {%>
      <tr> 
        <td><%= users[i].name%></td>
        <td><%= users[i].age%></td>
        <td><%= users[i].gender%></td>
      </tr>
      <%}%>
    </table>
    <h2>Using for-of to loop array</h2>
    <table>
      <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Gender</th>
      </tr>
      <% for(let user of users) {%>
      <tr> 
        <td><%= user.name%></td>
        <td><%= user.age%></td>
        <td><%= user.gender%></td>
      </tr>
      <%}%>
    </table>
    <h2>Using forEach to loop array</h2>
    <table>
      <tr>
        <th>Name</th>
        <th>Age</th>
        <th>Gender</th>
      </tr>
      <% users.forEach(user => {%>
      <tr> 
        <td><%= user.name%></td>
        <td><%= user.age%></td>
        <td><%= user.gender%></td>
      </tr>
      <%});%>
    </table>
  </body>
</html>

In the code all of the mentioned loops are used to show iteration of an array in EJS template. For each loop, JavaScript code is enclosed with in the scriptlet tags.

So, the loop and starting curly bracket is in a scriptlet tag

<% for(let user of users) {%>

Then the closing curly bracket is in a scriptlet tag

<%}%>

When you run the file- node app.js and then access the URL- http://localhost:3000/user

EJS Template Iteration Example

EJS object iteration ExpreeeJS example

If you want to iterate an object and extract the (key, value) pairs then you can use for-in loop.

app.js

const express = require('express');

const app = express();

const port = 3000;
const path = require('path');

// To serve static files like CSS
app.use(express.static(path.join(__dirname, 'public')));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// Hardcoded user data
const user = {name:'Reene', age: 28, gender:'F'};

app.get('/user', (req, res) => {
    res.render('user', {user: user, pageTitle: 'User Page'});
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

views\user.ejs

<!DOCTYPE html>
<html lang="en">
  <head>
    <title><%= pageTitle%></title>
    <link rel="stylesheet" href="/css/user.css">
  </head>
  <body> 
    <h2>Using for-in loop</h2>
    <ul>
      <% for(let key in user) {%>
        <li><%=key.charAt(0).toUpperCase() + key.substr(1).toLowerCase() + ': ' + user[key]%></li>
      <%}%>
    </ul>
  </body>
</html>

When you run the file- node app.js and access the URL- http://localhost:3000/user

you'll get the result as-

Using for-in loop

    Name: Reene
    Age: 28
    Gender: F

That's all for the topic ExpressJS: EJS Template Iteration Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment