0
0
Expressframework~30 mins

Passing data to templates in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Passing Data to Templates in Express
📖 Scenario: You are building a simple web page using Express.js that shows a list of fruits and their colors. You want to pass this data from your server code to the template so it can display the list dynamically.
🎯 Goal: Create an Express app that sends a list of fruits with their colors to a template. The template will then show each fruit and its color on the web page.
📋 What You'll Learn
Create a data object with fruit names and their colors
Set up a configuration variable for the page title
Pass the data and title to the template using res.render
Add the template code to display the fruit list and title
💡 Why This Matters
🌍 Real World
Passing data to templates is how web servers send dynamic content to users, like showing product lists or user profiles.
💼 Career
Understanding how to pass data to templates is essential for backend web developers working with Express and similar frameworks.
Progress0 / 4 steps
1
Create the fruit data object
Create a constant called fruits that is an array of objects. Each object should have name and color properties with these exact entries: { name: 'Apple', color: 'Red' }, { name: 'Banana', color: 'Yellow' }, { name: 'Grape', color: 'Purple' }.
Express
Need a hint?

Use const fruits = [ ... ] with objects inside the array.

2
Add a page title variable
Create a constant called pageTitle and set it to the string 'Fruit Colors'.
Express
Need a hint?

Use const pageTitle = 'Fruit Colors';

3
Pass data to the template in the route
Inside your Express app, create a GET route for '/'. Use res.render to render the template named 'fruits' and pass an object with fruits and pageTitle as properties.
Express
Need a hint?

Use app.get('/', (req, res) => { res.render('fruits', { fruits, pageTitle }); });

4
Create the template to display the data
In your template file named fruits.ejs, add an <h1> tag that shows the pageTitle. Then add an unordered list <ul> that loops over fruits and displays each fruit's name and color inside a <li>.
Express
Need a hint?

Use EJS syntax: <% fruits.forEach(fruit => { %> and <%= fruit.name %>