1. Fundamentals
Views in Express.js are template files used to generate dynamic HTML pages on the server before sending them to the browser. They allow you to:
- Insert dynamic data into HTML (e.g., user names, blog posts)
- Reuse HTML components (headers, footers, navbars)
- Keep your code clean by separating logic from presentation
1. π§ Setting Up Views in Express
1.1 Choose a Templating Engine
Templating engines allow you to use dynamic code inside your HTML. Popular ones include:
EJS
(Embedded JavaScript)Pug
(formerly Jade)Handlebars
Weβll use EJS here.
2.2 Install EJS
npm install ejs
2.3 Configure Express to Use Views
const express = require('express');const app = express();
// Set the view engine to ejsapp.set('view engine', 'ejs');
// Set the directory for view templates (optional if default is used)app.set('views', './views');
1.4 Create a View File
views/index.ejs
:
<!DOCTYPE html><html><head> <title><%= title %></title></head><body> <h1>Hello, <%= name %>!</h1></body></html>
Directory Structure
project/βββ views/β βββ index.ejsβ βββ about.ejsβββ public/β βββ style.cssβββ app.js
You can also use partials (reusable view components) and layout systems (with tools like express-ejs-layouts
).
1.5 Render the View in a Route
app.get('/', (req, res) => { res.render('index', { title: 'Welcome Page', name: 'Nadith' });});
When a user accesses /
, Express will:
β
Find views/index.ejs
β
Fill in the <%= %>
values
β
Send the resulting HTML to the browser
2. π§ Why Use Views?
Feature | Benefit |
---|---|
Dynamic pages | Show user-specific content (e.g., dashboards) |
Template reuse | Common layouts (headers, footers) across pages |
Cleaner code | Separate logic (routes ) from HTML (views ) |
Server-side rendering | Good for SEO, and fast first-page loads |
3. π Example with Route Params
app.get('/hello/:user', (req, res) => { res.render('index', { title: 'Hello Page', name: req.params.user });});
Visit /hello/Alex
β βHello, Alex!β
π§ͺ Summary
Concept | Description |
---|---|
app.set('view engine', 'ejs') | Sets templating engine |
res.render('view', data) | Renders the view and injects data |
<%= %> in template | Embeds dynamic data in HTML |