0
0
Expressframework~5 mins

Passing data to templates in Express

Choose your learning style9 modes available
Introduction

Passing data to templates lets you show dynamic content on web pages. It helps you send information from your server to the page users see.

You want to show a user's name on a welcome page after login.
You need to display a list of products fetched from a database.
You want to show error messages or success notifications after a form submission.
You want to customize page content based on user preferences.
You want to display the current date or time on a page.
Syntax
Express
res.render('templateName', { key1: value1, key2: value2 })
The first argument is the template file name without extension.
The second argument is an object with data you want to use inside the template.
Examples
This sends a title variable with value 'Welcome Home' to the 'home' template.
Express
res.render('home', { title: 'Welcome Home' })
This sends username and age to the 'profile' template for dynamic display.
Express
res.render('profile', { username: 'Alice', age: 30 })
This sends an error message to the 'error' template to show to the user.
Express
res.render('error', { message: 'Page not found' })
Sample Program

This Express app sends a user object to the 'index' template. The template uses the data to greet the user by name and show their age.

Express
import express from 'express';
const app = express();
app.set('view engine', 'ejs');

app.get('/', (req, res) => {
  const user = { name: 'Sam', age: 25 };
  res.render('index', { user });
});

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

// index.ejs template content:
// <h1>Hello, <%= user.name %>!</h1>
// <p>You are <%= user.age %> years old.</p>
OutputSuccess
Important Notes

Make sure your template engine (like EJS) is installed and set up correctly.

Data keys become variables inside the template for easy use.

Passing complex objects is allowed, not just simple strings or numbers.

Summary

Use res.render() to send data to templates in Express.

Pass an object with keys and values as the second argument.

Templates use these keys as variables to show dynamic content.