Nearby lessons

8 of 14

πŸ“„ EJS Template Engine in Express JS & Node JS | Embedded JavaScript | View Engine

πŸ“Œ What is EJS?

πŸ’‘ What is EJS (Embedded JavaScript)?

EJS is a powerful and popular template engine for Node.js, used to create dynamic HTML pages using JavaScript.

It allows us to insert variables, run JavaScript logic, loop through data, render lists, handle forms, and more β€” all inside HTML files with .ejs extension.

A template engine helps generate dynamic pages with minimal code by injecting server-side data into HTML.

πŸ“˜ EJS Syntax Tags

TagDescriptionNotes
<% %>Control flow (no output)Used for loops & conditionals
<%= %>Escaped OutputSafe output (prevents XSS)
<%- %>Unescaped OutputUnsafe β€” renders raw HTML
<%# %>CommentIgnored in output
<%-\ %>Remove following newlineWhitespace control
<%_ %>Trim whitespace beforeCleaner HTML output
%_>Trim whitespace afterCleaner HTML output

πŸ“ Step 1: Project Structure

project-folder/
 ┣ πŸ“ views
 ┃ ┣ πŸ“„ about.ejs
 ┃ ┣ πŸ“„ about1.ejs
 ┃ β”— πŸ“„ form.ejs
 β”— πŸ“„ index.js
        

βš™οΈ Step 2: Setup Express with EJS

Install the required packages and configure Express to use EJS as the view engine.

Express.js Server
NODE RUNTIME
// Install packages: npm install express ejs
const express = require('express');
const app = express();

// --- Core Configuration ---
// Step 1: Set the template engine to EJS
app.set('view engine', 'ejs');

// Step 2: Middleware to parse URL-encoded bodies (for form handling)
app.use(express.urlencoded({ extended: false }));

// Step 3: Middleware to serve static files from the 'public' folder (CSS, images)
app.use(express.static('public')); 

// --- Route Definitions (see below) ---

// Step 4: Start the Server (Must be at the end)
app.listen(8080, () => {
    console.log("Server running at http://localhost:8080");
});
Browser Output
Server logs

🏠 Step 3: Home Route (Simple Response)

Basic route returning plain HTML.

Express.js Server
NODE RUNTIME
const express = require('express');
const app = express();

app.set('view engine', 'ejs');

app.get('/', (req, res) => {
    res.send("<h1>Home Page</h1>");
});

app.listen(8080, () => console.log("Server running at http://localhost:8080"));

Browser Output
Server logs

πŸ“„ Step 4: Render Static EJS Page

Use res.render() to load EJS files from the views folder.

Express.js Server
NODE RUNTIME
const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());
app.set('view engine', 'ejs');

app.get('/', (req, res) => {
    res.render("about"); 
});

app.listen(8080, () => {
    console.log("Server running at http://localhost:8080");
});
Browser Output
Server logs

πŸ“Œ Step 5: Pass Dynamic Data (Variables)

Send data from Express to EJS using objects.

Express.js Server
NODE RUNTIME
const express = require('express');
const app = express();

app.set('view engine', 'ejs'); // Enables EJS templating engine

app.get('/about', (req, res) => {
    res.render("about", {
        title: 'About Page',
        message: 'Welcome to Learn EJS!'
    });
});

app.listen(8080, () => {
    console.log("Server running at http://localhost:8080");
});

Browser Output
Server logs

🍎 Step 6: Pass Array to EJS

Loop through array using EJS tags.

Express.js Server
NODE RUNTIME
const express = require('express');
const app = express();

app.set('view engine', 'ejs'); // Enables EJS templating engine
app.get('/about', (req, res) => {
    let items = ['Apple', 'Banana', 'Mango'];
    res.render("about", {
        title: 'About Page',
        message: 'Welcome to Learn EJS!',
        items: items
    });
});

app.listen(8080, () => {
    console.log("Server running at http://localhost:8080");
});
Browser Output
Server logs

🧍 Step 7: Pass Array of Objects

Create dynamic tables using EJS loops.

Express.js Server
NODE RUNTIME
const express = require('express');
const app = express();

app.set('view engine', 'ejs'); // Enables EJS templating engine

app.get('/about', (req, res) => {
    const users = [
        { name: 'Akshay Kumar', age: 25, city: 'Delhi' },
        { name: 'Salman Khan', age: 24, city: 'Mumbai' },
        { name: 'Shahid Kapoor', age: 23, city: 'Goa' },
        { name: 'John Abraham', age: 22, city: 'Delhi' },
        { name: 'Katrina Kaif', age: 23, city: 'Agra' }
    ];
    res.render("about", {
        title: 'About Page',
        message: 'Welcome to Learn EJS!',
        users: users
    });
});

app.listen(8080, () => {
    console.log("Server running at http://localhost:8080");
});
Browser Output
Server logs

πŸ“ Step 8: Form Handling (GET)

Render a form using an EJS template.

Express.js Server
NODE RUNTIME
const express = require('express');
const app = express();

app.set('view engine', 'ejs'); // Enables EJS templating engine

app.get('/form', (req, res) => {
    res.render('form', { message: null });
});

app.listen(8080, () => {
    console.log("Server running at http://localhost:8080");
});
Browser Output
Server logs

πŸ“¨ Step 9: Form Handling (POST)

Access req.body and send data back to EJS.

Express.js Server
NODE RUNTIME
const express = require('express');
const app = express();

app.set('view engine', 'ejs'); // Enables EJS templating engine
app.use(express.urlencoded({ extended: false }));

app.post('/submit', (req, res) => {
    const name = req.body.myname;
    const message = `Hello, ${name}! You submitted the form.`;
    res.render('form', { message: message }); // Show message on same page
});

app.listen(8080, () => {
    console.log("Server running at http://localhost:8080");
});
Browser Output
Server logs

πŸ“˜ Step 10: Multiple EJS Pages

Rendering multiple EJS views from different routes.

Express.js Server
NODE RUNTIME
const express = require('express');
const app = express();

app.set('view engine', 'ejs'); // Enables EJS templating engine

app.get('/about', (req, res) => {
    const users = [
        { name: 'Akshay Kumar', age: 25, city: 'Delhi' },
        { name: 'Salman Khan', age: 24, city: 'Mumbai' },
        { name: 'Shahid Kapoor', age: 23, city: 'Goa' },
        { name: 'John Abraham', age: 22, city: 'Delhi' },
        { name: 'Katrina Kaif', age: 23, city: 'Agra' }
    ];
    res.render("about1", {
        title: 'About Page',
        message: 'Welcome to Learn EJS!',
        users: users
    });
});

app.listen(8080, () => {
    console.log("Server running at http://localhost:8080");
});
Browser Output
Server logs

🧠 Test Your Knowledge

5 Questions

Progress: 0 / 5
Keep Going!Loops & Logics in EJS