Passing Data to Templates
One of the most powerful features of EJS is passing data from your Express routes to your templates. The res.render() method accepts a second argument — an object containing the data you want available in your template.
app.get('/profile', (req, res) => {
res.render('profile', {
name: 'Bilal',
age: 25,
role: 'Developer'
});
});
Inside your EJS file, you can access these variables directly by name. Express makes them available in the template's scope.
<h1>Hello, <%= name %></h1>
<p>Age: <%= age %></p>
<p>Role: <%= role %></p>
Try it Yourself →
Passing Arrays to Templates
You can pass arrays to EJS templates just as easily as simple values. This is perfect for rendering lists, tables, or any repeated content.
app.get('/students', (req, res) => {
res.render('students', {
students: ['Ali', 'Sara', 'Omar', 'Layla']
});
});
In your template, use EJS tags with JavaScript to loop through the array.
<ul>
<% students.forEach(student => { %>
<li><%= student %></li>
<% }); %>
</ul>
Each item is rendered as a list element. You can use the same pattern for objects with key-value pairs.
Try it Yourself →Passing Objects to Templates
Objects let you group related data together. This keeps your route clean and your templates organized.
app.get('/product', (req, res) => {
res.render('product', {
product: {
name: 'Laptop',
price: 999,
inStock: true
}
});
});
Access nested properties using dot notation inside your EJS tags.
<h2><%= product.name %></h2>
<p>Price: $<%= product.price %></p>
<p>Available: <%= product.inStock ? 'Yes' : 'No' %></p>
Using Request Parameters in Templates
Route parameters from Express can be passed directly to your templates. This is useful for dynamic pages like user profiles or product details.
app.get('/user/:id', (req, res) => {
res.render('user', {
userId: req.params.id
});
});
The :id parameter is captured from the URL and passed to the template. You can then display it or use it to fetch more data.
<h1>User Profile #<%= userId %></h1>
<p>Welcome to your dashboard.</p>
Try it Yourself →
Query Strings in Templates
Query strings from the URL are available through req.query. Pass them to your template to display or filter data dynamically.
app.get('/search', (req, res) => {
res.render('search', {
query: req.query.q,
page: req.query.page || 1
});
});
When a user visits /search?q=javascript&page=2, the template receives the search term and page number.
<h1>Search Results for: <%= query %></h1>
<p>Page: <%= page %></p>
This pattern is essential for building search interfaces, paginated lists, and filterable content.