Labs ICT
⭐ Pro Login

Working with Variables

Passing and rendering data in templates.

Passing Data to Templates

When you render an EJS template, you pass an object with all the data it needs. Think of it as handing your template a toolbox full of everything it needs to build the page.


res.render('profile', {
  name: 'Alice',
  age: 25,
  isAdmin: true
});
    

Now these variables are available in your template. Easy, right?

Accessing Variables

Use dot notation to access nested properties. EJS handles this naturally:


Name: <%= user.name %>

Email: <%= user.email %>

City: <%= user.address.city %>

If you pass a flat object, just use the property names directly. For nested objects, chain the dots.

Try it Yourself β†’

Handling Undefined Values

What happens when a variable doesn't exist? EJS shows nothingβ€”no error, just empty space. That's usually fine, but sometimes you want a fallback.


Welcome, <%= user.name || 'Guest' %>!

Items: <%= cart.items.length || 0 %>

The double pipe operator gives you default values. If the left side is falsy, the right side kicks in. Trust me, you'll use this pattern constantly.

Null Safety

Be careful with deeply nested properties. If user is undefined, user.name throws an error. Use optional chaining or checks:


<% if (user && user.profile) { %>
  

<%= user.profile.bio %>

<% } %>

This defensive approach keeps your templates from crashing when data is missing.