0
0
ExpressHow-ToBeginner · 4 min read

How to Pass Data to Template in Express: Simple Guide

In Express, you pass data to a template by using res.render('templateName', dataObject). The dataObject contains key-value pairs that the template can use to display dynamic content.
📐

Syntax

The basic syntax to pass data to a template in Express is:

  • res.render('templateName', dataObject): Renders the template named templateName and passes dataObject to it.
  • templateName: The name of the template file without extension.
  • dataObject: An object containing keys and values accessible in the template.
javascript
res.render('templateName', { key1: 'value1', key2: 42 })
💻

Example

This example shows how to pass a user's name and age to a Pug template and display it on a web page.

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

const app = express();

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

app.get('/', (req, res) => {
  const userData = { name: 'Alice', age: 30 };
  res.render('profile', userData);
});

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

// Pug template file 'views/profile.pug':
// html
//   head
//     title User Profile
//   body
//     h1 Hello #{name}!
//     p You are #{age} years old.
Output
<!DOCTYPE html><html><head><title>User Profile</title></head><body><h1>Hello Alice!</h1><p>You are 30 years old.</p></body></html>
⚠️

Common Pitfalls

Common mistakes when passing data to templates include:

  • Not passing an object as the second argument to res.render.
  • Using incorrect keys that don't match the template variables.
  • Forgetting to set the template engine or views directory.
  • Trying to pass data asynchronously without waiting for it before rendering.
javascript
/* Wrong: Passing a string instead of an object */
res.render('profile', 'Alice');

/* Right: Pass an object with keys matching template variables */
res.render('profile', { name: 'Alice' });
📊

Quick Reference

Tips for passing data to templates in Express:

  • Always pass an object as the second argument to res.render.
  • Use descriptive keys that match your template variables.
  • Set your template engine with app.set('view engine', 'engineName').
  • Ensure your template files are in the correct views folder.

Key Takeaways

Use res.render('template', dataObject) to pass data to templates in Express.
The dataObject keys become variables accessible inside the template.
Always set the template engine and views directory before rendering.
Pass an object, not a string or other type, as the second argument to res.render.
Match your data keys exactly with the template variable names.