22. EJS (Embedded JavaScript)

Published: (April 30, 2026 at 11:36 AM EDT)
2 min read
Source: Dev.to

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

TagDescription
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
});
0 views
Back to Blog

Related posts

Read more »

Making my own framework. Any tips?

!Cover image for Making my own framework. Any tips?https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fde...