Setting Up EJS
EJS (Embedded JavaScript) is a simple template engine that lets you generate HTML with plain JavaScript. It uses special tags to embed dynamic data, loops, and conditionals directly in your HTML files.
EJS is one of the easiest template engines to learn because it uses regular JavaScript syntax. Unlike React or other frontend frameworks, EJS renders HTML on the server and sends the final HTML to the browser.
Example
// npm install ejs
const express = require('express');
const path = require('path');
const app = express();
// Set EJS as the view engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Serve static files
app.use(express.static('public'));
// Render a view with data
app.get('/', (req, res) => {
res.render('index', {
title: 'Home Page',
username: 'Alice',
items: ['Node.js', 'Express', 'EJS']
});
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
}); - app.set('view engine', 'ejs') — Tell Express to use EJS
- app.set('views', path) — Set the directory for template files
- res.render('name', data) — Render a template and send the HTML
- Views are stored as .ejs files in the views/ directory
- EJS uses <% %> tags to embed JavaScript in HTML
Notes
- EJS files have the .ejs extension and live in the views/ folder by default.
EJS Syntax and Partials
EJS uses special tags to embed JavaScript in HTML. The most common are: <%= %> for outputting values, <% %> for control flow (loops, conditionals), and <%- %> for outputting unescaped HTML.
Partials let you reuse common sections like headers, footers, and navigation bars across multiple pages.
Example
<!-- views/index.ejs -->
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<%- include('partials/header') %>
<h1>Welcome, <%= username %>!</h1>
<% if (items.length > 0) { %>
<ul>
<% items.forEach(item => { %>
<li><%= item %></li>
<% }) %>
</ul>
<% } else { %>
<p>No items found.</p>
<% } %>
<%- include('partials/footer') %>
</body>
</html>
<!-- views/partials/header.ejs -->
<header>
<nav>
<a href="/">Home</a>
<a href="/about">About</a>
</nav>
</header>
<!-- views/partials/footer.ejs -->
<footer>
<p>© 2025 My App</p>
</footer> Notes
- Use <%= %> for escaped output (safe from XSS). Use <%- %> for unescaped HTML (only for trusted content like partials). Never use <%- %> with user input.
