npm install express ejs
Step 2: Create Your .html Templates
my-express-app/
├── node_modules/
├── views/
│ ├── index.ejs
├── index.js
├── package.json
Create an index.
ejs file inside the views
directory with the HTML content you want to render. For example:
<!DOCTYPE html>
<html>
<head>
<title>Welcome to My Express App</title>
</head>
<body>
<h1>Hello, Express with EJS!</h1>
</body>
</html>
Step 3: Set Up Your Express App with EJS
const express = require("express");
require('dotenv').config();
const app = express();
app.use(express.json());
// Configure Express to use EJS as the template engine
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.get('/', (req, res) => {
// Render the 'index' template (without the .html extension)
res.render('index');
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`SERVER STARTED with ${port}`);
});
Passing data
app.get('/', (req, res) => {
const data = {
name: 'Bard',
email: 'bard@example.com',
};
// Render the 'index' template (without the .html extension)
res.render('index',data);
});
index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
your name : <%= name %>
</body>
</html>