/index.js
// Import required modules
const express = require('express');
const path = require('path');
// Create an Express application
const app = express();
// Define the port
const port = 3000;
// Set EJS as the view engine
app.set('view engine', 'ejs');
// Set the views directory
app.set('views', path.join(__dirname, 'views'));
app.get('/', (req, res) => {
// Sending this data from the server
const data = {
name: 'Geeks!',
isAdmin: true,
items: [
'Apple',
'Banana',
'Orange',
'Grapes',
'Mango'
]
};
// Render the EJS template and pass the data
res.render('index', data);
});
// Start the server
app.listen(port, () => {
console.log(
`Server is running at http://localhost:${port}`
);
});
views/index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>EJS Example</title>
<style>
h1 { color: green; }
</style>
</head>
<body>
<!-- Include Header File -->
<%- include('header') %>
<!-- Conditional Example -->
<% if (isAdmin) { %>
<p>Welcome, Admin!</p>
<% } else { %>
<p>Welcome, User!</p>
<% } %>
<!-- Loop Example -->
<ul>
<% items.forEach(function(item) { %>
<li>
<%= item %>
</li>
<% }); %>
</ul>
</body>
</html>