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
| Tag | Description | Notes |
|---|---|---|
| <% %> | Control flow (no output) | Used for loops & conditionals |
| <%= %> | Escaped Output | Safe output (prevents XSS) |
| <%- %> | Unescaped Output | Unsafe β renders raw HTML |
| <%# %> | Comment | Ignored in output |
| <%-\ %> | Remove following newline | Whitespace control |
| <%_ %> | Trim whitespace before | Cleaner HTML output |
| %_> | Trim whitespace after | Cleaner 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.
π Step 3: Home Route (Simple Response)
Basic route returning plain HTML.
π Step 4: Render Static EJS Page
Use res.render() to load EJS files from the views folder.
π Step 5: Pass Dynamic Data (Variables)
Send data from Express to EJS using objects.
π Step 6: Pass Array to EJS
Loop through array using EJS tags.
π§ Step 7: Pass Array of Objects
Create dynamic tables using EJS loops.
π Step 8: Form Handling (GET)
Render a form using an EJS template.
π¨ Step 9: Form Handling (POST)
Access req.body and send data back to EJS.
π Step 10: Multiple EJS Pages
Rendering multiple EJS views from different routes.