Open In App

How To Render Dynamic Lists Using EJS and Express ?

Last Updated : 09 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Rendering of dynamic lists in EJS and Express mainly allows us to dynamically generate the HTML content which is based on the data from the backend server. We can render dynamic lists using the '<% %>' tags.

Steps to Render Dynamic Lists

Step 1: Create a directory for the project

mkdir root
cd root

Step 2: Initialize the Node Application

npm init -y

Step 3: Install the required dependencies

npm i express ejs

Project Structure

Create the required files and folder as shown here

Dependencies

"dependencies": { 
"express": "^4.18.2",
"ejs": "^3.1.9",
}

Step 4: Setting up the Express App

First, create a file named app.js and initialize your Express application (if not done already)

JavaScript
//app.js

const express = require('express');
const app = express();
const port = 3000;

app.set('view engine', 'ejs');
app.use(express.static('public'));

app.get('/', (req, res) => {
    res.render('index', { data: [], showButton: true });
});

app.get('/list', (req, res) => {
    const data = ['JavaScript', 'Node.js', 'Express', 'EJS'];
    res.render('index', { data: data, showButton: false });
});

app.listen(port, () => {
    console.log(`Server is running at http://localhost:${port}`);
});
  • Set the view engine: app.set('view engine', 'ejs') specifies that we’re using EJS for templating.
  • Serve static files: app.use(express.static('public')) allows serving static assets like CSS and images.
  • Routes:
    • /: Renders the page with an empty list and a button.
    • /list: Renders the page with a predefined list and hides the button

Step 5: Creating the EJS Template

Create a file named index.ejs in the views folder with the following content:

HTML
//index.ejs

<html>
<head></head>
<body>
    <h1 style="color: green;">GeeksforGeeks</h1>
    <h3>Rendering Dynamic List</h3>
    <% if (showButton) { %>
        <form action="/list" method="get">
            <button type="submit">Show List</button>
        </form>
        <% } %>
            <ul>
                <% data.forEach(item=> { %>
                    <li>
                        <%= item %>
                    </li>
                    <% }); %>
            </ul>
</body>
</html>
  • Conditional Rendering: <% if (showButton) { %>: Displays a button if showButton is true.
  • Dynamic List Rendering: <% data.forEach(item => { %>: Iterates over the data array to create list items dynamically.
  • Output Escaping: <%= item %>: Outputs the item safely to prevent XSS attacks.

To run the application, we need to start the server by using the below command.

node server.js

Output


Next Article

Similar Reads