Home > OS >  Express nodejs Handlebars not rendering database content correctly inside EJS file
Express nodejs Handlebars not rendering database content correctly inside EJS file

Time:12-03

Im having a problem with my express nodejs project where the handlebars wont render on my ejs file. I created some handlebars which fetch some data from a database. When I render the hbs files the content from the database is displayed correctly, but when I include the hbs files in my ejs file together with my page header and footer the content from the database is not retrieved. I would appreciate any help.

cars.hbs

<!DOCTYPE html>
<html>
    <body>
        <p> The {{dbcars.model}} features a {{dbcars.specs.engine}} engine...  </p>
    </body>
</html>

home.ejs

<body>

<p> <%- include('navbar.ejs') %> </p>

<p> <%- include('handlebars/cars.hbs') %> </p>

<p> <%- include('footer.ejs') %> </p>

</body>
</html>

(note: when I render (handlebars/cars.hbs) instead of (home.ejs) the handlebars render correctly. )

car.js

router.get('/vehicle/:id', async (req, res) => {
  Car.findById(req.params.id, function(err, carRouter) {
    res.render("home.ejs", {
        dbcar: carRouter
    })

This is the result im getting:

(navbar)
The {{dbcars.model}} features a {{dbcars.specs.engine}} engine... 
(footer)

This is the result im trying to get:

(navbar)
The Nissan Sentra features a 2.0 L 4-cylinder engine...
(footer)

CodePudding user response:

You should create cars.ejs as well

cars.ejs

<% if (dbcar.length > 0) { %> 
  <% dbcar.forEach(dbcars => { %>
  <p> The <%= dbcars.model %> features a <%= dbcars.specs.engine %> engine...  </p>
  <% }) %>
<% } else { %>
  <p>There is no information to display.</p>
<% } %>

home.ejs

  <%- include('handlebars/cars.ejs'); %>

car.js

router.get('/vehicle/:id', async (req, res) => {
  Car.findById(req.params.id, function(err, carRouter) {
    res.render("cars.ejs", {
      dbcar: carRouter
    })
  };
};
  • Related