Episode 7 of 12
View Engines (EJS)
Learn how to use EJS (Embedded JavaScript) as a view engine to create dynamic HTML templates in your Express applications.
View engines allow you to create dynamic HTML pages by embedding data into templates. EJS (Embedded JavaScript) is one of the most popular view engines for Express.
Setting Up EJS
npm install ejs
const express = require('express');
const app = express();
// Set EJS as the view engine
app.set('view engine', 'ejs');
app.listen(3000);
By default, Express looks for view templates in a views/ folder.
Creating EJS Templates
Create views/index.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
</head>
<body>
<h1>Welcome, <%= name %>!</h1>
<p>Today is <%= new Date().toDateString() %></p>
</body>
</html>
Rendering Views with Data
app.get('/', (req, res) => {
res.render('index', {
title: 'Home',
name: 'NoteArc Reader'
});
});
EJS Tags
<%= %>— Output the value (HTML escaped)<%- %>— Output raw HTML (unescaped)<% %>— Execute JavaScript (no output)
Loops and Conditionals
<ul>
<% blogs.forEach(blog => { %>
<li><%= blog.title %> - <%= blog.author %></li>
<% }) %>
</ul>
<% if (blogs.length === 0) { %>
<p>No blogs to display.</p>
<% } %>
Partials
Reuse common HTML (like headers and footers) with partials:
<%- include('./partials/nav') %>
<h1>Page Content</h1>
<%- include('./partials/footer') %>
Partials keep your code DRY and your templates clean.