使用 hbs 显示相同页面的路由

routing with hbs displaying the same page

我将一个路由设置为主页,其他路由设置为显示其他页面,但每当我 运行 主页以外的其他路由时,它仍然显示主页

这是我的视图目录设置

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 在根文件夹中有以下用于 hbs 设置的代码

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");

和路由器

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",
  });
});

但是所有路由都呈现 main 页面。请帮忙谢谢

 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
);

像这样设置你的引擎。 看来你没有给出正确的默认布局名称, 您可能还想像这样向控制器添加布局

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

您应该在这样渲染时通过添加 layout: false 来停用默认布局

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

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",
    layout: false
  });
});