22. EJS (Embedded JavaScript)
Source: Dev.to
What is EJS?
EJS (Embedded JavaScript) is a templating engine for Node.js.
Key Concepts
- Templating – Generate dynamic HTML using JavaScript.
- Separation of Concerns – Front‑end (HTML, CSS) vs. back‑end (JavaScript).
- Other Templating Languages – Python (Jinja), PHP (Twig), JavaScript (EJS).
- How EJS Works – JavaScript runs inside HTML; “ outputs data to the page.
Rendering with Express
Static file
res.sendFile("index.html");Dynamic (EJS) file
app.post("/submit", (req, res) => {
res.render("index.ejs", {
name: req.body["name"]
});
});
## Hello
EJS Tags
| Tag | Description |
|---|---|
| “ | Output the value (escaped). |
| “ | Execute JavaScript (no output). |
| “ | Render raw HTML (unescaped). |
| “ | Display “ literally. |
| “ | Comment – not executed. |
| “ | Include a partial (e.g., header, footer). |
Passing Data
- Server → EJS – Pass data via
res.render(). - EJS → Server – Use forms with
method="POST"to send data back.
// Example: rendering with data
app.get("/", (req, res) => {
res.render("index.ejs", { title: "Home", items: ["A", "B", "C"] });
});If no data is provided, use default values or app.locals.
Partials & Layouts
// Serve static assets
app.use(express.static("public"));Templating Syntax Recap
- “ – Logic / control flow.
- “ – Escaped output.
- “ – Unescaped (raw) output.
Using Partials
Partials help avoid code duplication and improve maintainability.
JavaScript Tip
Variable declarations
const– cannot be reassigned.let– can be reassigned.
Array iteration
array.forEach((element, index, array) => {
// your code here
});