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
Section titled β1. π§ Setting Up Views in Expressβ1.1 Choose a Templating Engine
Section titled β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
Section titled β2.2 Install EJSβnpm install ejs2.3 Configure Express to Use Views
Section titled β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
Section titled β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
Section titled βDirectory Structureβproject/βββ views/β βββ index.ejsβ βββ about.ejsβββ public/β βββ style.cssβββ app.jsYou can also use partials (reusable view components) and layout systems (with tools like express-ejs-layouts).
1.5 Render the View in a Route
Section titled β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?
Section titled β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
Section titled β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
Section titled βπ§ͺ 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 |