Integrating Arrays of Objects into EJS Templates
EJS templates allow you to embed JavaScript code directly into your HTML markup. This makes it straightforward to iterate over arrays of objects and dynamically generate HTML content based on the data.
Step 1: Create a project folder using the following command.
mkdir ejs-array-example
cd ejs-array-example
Step 2: Initialize the node project.
npm init -y
Step 3: Install the required dependencies:
npm install express ejs
Folder Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"ejs": "^3.1.9",
"express": "^4.18.3"
}
Example: Create the required files as suggested in folder structure and add the following code.
HTML
<!-- views/users.ejs --> <!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >User List</ title > </ head > < body > < h1 >User List</ h1 > < ul > <% users.forEach(user=> { %> < li >ID: <%= user.id %>, Name: <%= user.name %>, Age: <%= user.age %> </ li > <% }); %> </ ul > </ body > </ html > |
Javascript
// server.js const express = require( 'express' ); const app = express(); const port = 3000; // Set the view engine to EJS app.set( 'view engine' , 'ejs' ); // Define a route to render the EJS template app.get( '/' , (req, res) => { // Sample array of user objects const users = [ { id: 1, name: 'Ram' , age: 30 }, { id: 2, name: 'Shyam' , age: 25 }, { id: 3, name: 'Hari' , age: 40 } ]; // Render the EJS template with the users data res.render( 'users' , { users: users }); }); // Start the server app.listen(port, () => { console.log(`Server is running on http: //localhost:${port}`); }); |
To start the application run the following command:
node server.js
Output:
How to use array of objects in EJS Template Engine ?
Arrays of objects are collections of JavaScript objects stored within an array. Each object within the array can contain multiple key-value pairs, making them versatile for organizing various types of data. For example, you might have an array of objects representing users, products, or posts in a social media application.
Here’s an example of an array of objects representing users:
Javascript
const users = [ { id: 1, name: 'Ram' , age: 30 }, { id: 2, name: 'Shyam' , age: 25 }, { id: 3, name: 'Hari' , age: 40 } ]; |