res.render helps you show web pages using templates. It fills in data and sends the final page to the browser.
0
0
res.render for templates in Express
Introduction
When you want to show a dynamic web page with changing content.
When you separate your HTML layout from your data in your app.
When you want to reuse the same page design but with different information.
When you want to send a complete HTML page as a response to a user request.
Syntax
Express
res.render(view, [locals], callback)
view is the template file name without extension.
locals is an optional object with data to fill in the template.
Examples
Render the 'index' template without extra data.
Express
res.render('index')Render 'profile' template and fill it with name and age.
Express
res.render('profile', { name: 'Alice', age: 30 })
Render 'error' template and handle the result with a callback.
Express
res.render('error', { message: 'Page not found' }, (err, html) => { if (err) console.error(err); else res.send(html); })
Sample Program
This Express app uses res.render to show the 'index' template. It sends a title and message to fill the page.
Express
import express from 'express'; const app = express(); app.set('view engine', 'pug'); app.get('/', (req, res) => { res.render('index', { title: 'Home Page', message: 'Welcome to our site!' }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
OutputSuccess
Important Notes
Make sure to set the template engine with app.set('view engine', 'yourEngine') before using res.render.
Templates usually live in a folder named views in your project root.
If you pass data in locals, you can use it inside your template to show dynamic content.
Summary
res.render creates a web page from a template and data.
Use it to send dynamic HTML pages to users.
Remember to set your template engine and keep templates in the views folder.