Search code examples
htmlnode.jsexpressexpress-handlebars

routing with hbs displaying the same page


I have a route set to a main page and other routes set display other pages but whenever I run a different route other than the main page, it still displays the main page

this is my views directory setup

views
    -partials
            -header.hbs
            -footer.hbs
            -navigation.hbs
            -index.hbs
    -main.hbs
    -portfolio.hbs
    -graphicsDisplay.hbs

main.hbs

{{!-- header partial file --}}
{{>header}}

{{!-- navigation partial file --}}
{{>navigation}}

{{!-- index partial file --}}
{{>index}}
 
{{!-- footer partial file --}}
{{>footer}}

portfolio.hbs

{{!-- header partial file --}}
{{>header}}

{{!-- navigation partial file --}}
{{>navigation}}

{{!-- footer partial file --}}
{{>footer}}

index.js in the root folder has the following code for hbs setup

const hbs = require("express-handlebars");
app.set("view engine", "hbs");
app.engine(
  "hbs",
  hbs({
    extname: "hbs",
    defaultView: "default",
    layoutsDir: path.join(__dirname, "views"),
    partialsDir: path.join(__dirname, "views/partials"),
  })
);

//calling router
app.use("/", require("./server/router/router.js"));

app.listen(3002);
console.log("listening to port 3002");

and the routers

router.get("/portfolio", (req, res) => {
  res.render("portfolio", {
    pageTitle: "MickyDesigns - Welcome to my portfolio showroom",
  });
});

router.get("/graphics", (req, res) => {
  const image = await UploadModel.find();
  res.render("graphicsDisplay", { images: image });
});

router.get("/", (req, res) => {
  res.render("main", {
    pageTitle:
      "MickyDesigns - Brand Management and Software development Projects",
  });
});

But all routes render the main page. Please help thanks


Solution

  •  app.set("view engine", "hbs");
    
    const handleEngine = hbs.create({
      defaultLayout:'main',
      extname:".hbs",
      layoutsDir: path.join(__dirname, "views/"),
      partialsDir:path.join(__dirname, "views/partials")
    })
    
    app.engine(
      "hbs",
      handleEngine.engine
    );
    

    setup your engine like this. it seems you were not giving the right default layout name, you might also want to be adding layouts to controllers like this

    exports.graphicsDisplay = async (req, res) => {
      ......
      res.render("graphicsDisplay",  { images: image , layout:'graphicsDisplay' });
    };