0
0
ExpressHow-ToBeginner · 3 min read

How to Render View in Express: Simple Guide

In Express, you render a view using the res.render() method inside a route handler. This method takes the view file name and an optional data object to pass variables to the template.
📐

Syntax

The basic syntax to render a view in Express is:

  • res.render(view, [locals], callback)

Here, view is the name of the template file (without extension), locals is an optional object with data to pass to the view, and callback is an optional function called after rendering.

javascript
res.render('viewName', { key: 'value' })
💻

Example

This example shows how to set up Express to render a simple view using the Pug template engine. It demonstrates passing data to the view and sending the rendered HTML to the browser.

javascript
import express from 'express';
import path from 'path';

const app = express();

// Set the view engine to Pug
app.set('view engine', 'pug');
// Set the views directory
app.set('views', path.join(process.cwd(), 'views'));

app.get('/', (req, res) => {
  res.render('index', { title: 'Welcome', message: 'Hello from Express!' });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000
⚠️

Common Pitfalls

Common mistakes when rendering views in Express include:

  • Not setting the view engine with app.set('view engine', 'yourEngine').
  • Incorrect views directory path causing Express to not find templates.
  • Forgetting to install or configure the template engine.
  • Passing incorrect or missing data objects to the view.

Example of a wrong and right way:

javascript
// Wrong: Missing view engine setup
app.get('/wrong', (req, res) => {
  res.render('index'); // This will cause an error if view engine is not set
});

// Right: Proper view engine setup
app.set('view engine', 'pug');
app.get('/right', (req, res) => {
  res.render('index', { title: 'Correct' });
});
📊

Quick Reference

  • res.render(view, data): Render a template with optional data.
  • app.set('view engine', engine): Define the template engine (e.g., 'pug', 'ejs').
  • app.set('views', path): Set the folder where templates are stored.
  • Ensure the template engine package is installed (e.g., npm install pug).

Key Takeaways

Always set the view engine with app.set('view engine', 'engineName') before rendering.
Use res.render('viewName', data) to send a rendered template as a response.
Place your template files in the directory set by app.set('views', path).
Install and configure the template engine package to avoid errors.
Pass data as an object to res.render to use dynamic content in views.