Basic

Dynamic pages with EJS

Hard-coding HTML is slow. EJS lets you write HTML once and fill in data from your server. Learn the `<%= %>` tag and pass data from a route into a template.

About 2 min of reading

Data Flow

A route passes data to an EJS template, the template engine mixes them into HTML, and the browser receives the finished page.
1 Route calls res.render('home', data)
↓
2 EJS loads the home.ejs template
↓
3 The engine runs each <%= %> tag
↓
4 Tags are replaced with real data
↓
5 A complete HTML string is produced
↓
6 The browser renders the page
Why this works
The EJS tags you will use

Only a handful of EJS tags appear in real projects:

  • <%= value %>: print a value (HTML-escaped for safety).
  • <%- value %>: print a value unescaped (risky, only with trusted HTML).
  • <% code %>: run JavaScript (loops, conditionals).
  • <!-- comment -->: HTML comments.

The escaped version (%=) is the default. It prevents a common web bug called cross-site scripting, where attacker input is turned into safe text instead of executable code.

Examples

A simple template

Create a folder views with home.ejs. EJS files are plain HTML with little tags:

<!doctype html>
<html>
  <body>
    <h1>Hello, <%= name %>!</h1>
  </body>
</html>

In your route, send the data:

app.get('/', (req, res) => {
  res.render('home', { name: 'Ada' });
});

The <%= name %> tag is replaced by the value of name. The browser shows Hello, Ada!. The same template can now greet anyone.

Loops in templates

EJS can loop over data directly in HTML:

<ul>
  <% items.forEach(function(item) { %>
    <li><%= item %></li>
  <% }); %>
</ul>

Send an array from your route:

res.render('home', { items: ['Apple', 'Banana', 'Cherry'] });

The browser shows three list items. Building a list of 100 products is now one loop, no copying and no pasting.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Serving HTML pages
Previous Lesson
Serving HTML pages
Next Lesson
Databases with SQLite
Databases with SQLite →