Open In App

How To Render Dynamic Lists Using EJS and Express ?

Last Updated : 29 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
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. We can use forEach loop to iterate through the data and dynamically generate HTML content for each item in the list. In this article, we will explore the detailed practical demonstration of Render Dynamic Lists Using EJS and Express.

Steps to Render Dynamic Lists Using EJS and Express:

Step 1: Firstly, we will make the folder named root by using the below command in the VScode Terminal. After creation use the cd command to navigate to the newly created folder.

mkdir root
cd root

Step 2: Once the folder is been created, we will initialize NPM using the below command, this will give us the package.json file.

npm init -y

Step 3: Once the project is been initialized, we need to install Express and EJS dependencies in our project by using the below installation command of NPM.

npm i express ejs

Project Structure:

The updated dependencies in package.json file will look like:

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

Example: Below is an example of rendering dynamic lists using EJS and Express.

HTML




<!DOCTYPE html>
 
<head>
    <title>GFG Example</title>
</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>


Javascript




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}`);
});


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

node server.js

Output:

Output



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads