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.

Example04
Loading editor…

🏠 Step 3: Home Route (Simple Response)

Basic route returning plain HTML.

Example05
Loading editor…

πŸ“„ Step 4: Render Static EJS Page

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

Example06
Loading editor…

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

Send data from Express to EJS using objects.

Example07
Loading editor…

🍎 Step 6: Pass Array to EJS

Loop through array using EJS tags.

Example08
Loading editor…

🧍 Step 7: Pass Array of Objects

Create dynamic tables using EJS loops.

Example09
Loading editor…

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

Render a form using an EJS template.

Example10
Loading editor…

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

Access req.body and send data back to EJS.

Example11
Loading editor…

πŸ“˜ Step 10: Multiple EJS Pages

Rendering multiple EJS views from different routes.

Example12
Loading editor…

🧠 Test Your Knowledge

5 Questions
Progress: 0 / 5