I am trying to render a trip object in an EJS template, but, I am getting the error
"ReferenceError: trip is not defined."
I have passed the trip object to the EJS template as a parameter, and I have checked the spelling of the variable name. I don’t know why I am getting this error.
Here is the code that I am using:
const trip = {type type: "national",
departure: "Paris",
destination: "Rome",
departureTime: "10:00 AM",
price: 100
};here
res.render('companyDashboard', { trip, company: req.user.company });
Here is the EJS template that I am using:
<p class="card-text">
<strong>Company :</strong> <%= company.company %><br>
<strong>Type :</strong> <%= trip.type %><br>
<strong>Departure :</strong> <%= trip.departure %><br>
<strong>Destination :</strong> <%= trip.destination %><br>
<strong>Departure Times :</strong>
<ul>
<% trip.departureTime.forEach(time => { %>
<li><%= time %></li>
<% }); %>
</ul>
<strong>Price :</strong> <%= trip.price %>
</p>
I would appreciate any help that you can provide.
I tried to render a trip object in an EJS template. I have expected the trip object to be rendered in the template, but, I got an error instead.
Here’s what I tried:
res.render('companyDashboard', { trip, company: req.user.company });
The trip object would be rendered in the companyDashboard template.
I got an error: ReferenceError: trip is not defined
.
2
Answers
Here the controller:
And the ejs code:
From your question, I noticed two issues in your code:
In the object declaration, you have a syntax error on the first line. You have written
type type: "national"
where it should betype: "national"
.In the EJS template, you are trying to use
forEach
ontrip.departureTime
as if it is an array, buttrip.departureTime
is a string, not an array.So first correct the object declaration:
Then, depending on your requirements:
If
departureTime
is supposed to be a single time string, remove theforEach
in the EJS template:If
departureTime
is supposed to be an array of times, change it to an array:And keep the
forEach
in the EJS template.