Even after passing the values to the ejs template, I am getting an error stating that the variables are not defined. I tried restarting the server but it didn’t work.
flightsController.js:
if (flight.length > 0) {
if (returnTicket) {
const returnFlight = await Flights.find({
sourceIATA: destinationIATA,
destinationIATA: sourceIATA,
});
if (returnFlight.length > 0) {
res.render("flights", { flight, returnFlight });
} else {
res.render("flights", { flight, noReturnFlights: true });
}
} else {
res.render("flights", { flight });
}
} else {
res.render("flights", { noFlightsAvailable: true });
}
flights.ejs:
<% if (flight && flight.length > 0) { %>
<h2>Flights:</h2>
<ul>
<% flight.forEach(flight => { %>
<li>Flight ID: <%= flight.flightId %></li>
<li>Source City: <%= flight.sourceCity %></li>
<li>Destination City: <%= flight.destinationCity %></li>
<!-- Display other flight details as needed -->
<br>
<% }); %>
</ul>
<% } %>
<% if (noReturnFlights) { %>
<h2>No Return Flights Available</h2>
<% } %>
<% if (noFlightsAvailable) { %>
<h2>No Flights Available</h2>
<% } %>
Example error (this is happening to all the variables):
flight is not defined
2
Answers
Are you using prettier ?
If yes i’ll have to tell you that prettier does not support EJS.
One solution is to work only with one of them…
I heard about plugin that allow to use both prettier and EJS but i never tried it. Here is the link if you are interested in it
https://socket.dev/npm/package/prettier-plugin-ejs
In the flightsController.js file, different local variables are set for the view when using res.render() calls. For example:
res.render("flights", { flight, returnFlight });
res.render("flights", { flight, noReturnFlights: true });
res.render("flights", { flight });
res.render("flights", { noFlightsAvailable: true });
However, the view file expects specific local variables
(flight, returnFlight, noReturnFlights, and noFlightsAvailable)
to be passed to it. In the first case, since noReturnFlights wasn’t passed but defined in the view file, it throws an error. Instead make a uniform call like this,res.render("flights", { flight , returnFlight: null,noReturnFlights: true , noFlightsAvailable: true });