Use multiples DefaultLayout (express-handlebars) in Nodejs: ( Error: ENOENT: no such file or directory )

Use multiples DefaultLayout (express-handlebars) in Nodejs: ( Error: ENOENT: no such file or directory )

我问我的问题

但是在我使用建议的解决方案后出现了这个错误:

Error: ENOENT: no such file or directory, open 'E:\test\views\layouts\index.handlebars'
structur of my code

我的代码结构:

views/
 themes
  theme1
   layouts/
    index.hbs
   content1.hbs
  theme2
   layouts/
    index.hbs
   content2.hbs
index.js

在 index.js 我使用这段代码:我在这行代码中添加文件夹布局:

_render.call(this, 'themes/' + theme + '/layouts/' + view, options, done);

所有代码(index.js):

 const express = require("express");
    const exphbs = require("express-handlebars");
    const app = express();




    app.use(function(req, res, next) {
      // cache original render
      var _render = res.render;

      res.render = function(view, options, done) {
        // custom logic to determine which theme to render
        var theme = getThemeFromRequest(req);
        // ends up rendering /themes/theme1/index.hbs
        _render.call(this, 'themes/' + theme + '/layouts/' + view, options, done);
      };
      next();
    });

    function getThemeFromRequest(req) {
      // in your case you probably would get this from req.hostname or something
      // but this example will render the file from theme2 if you add ?theme=2 to the url
      if(req.query && req.query.theme) {
        return 'theme' + req.query.theme;
      }
      // default to theme1
      return 'theme1';
    }

    // view enginge
    app.engine(
      "hbs",
      exphbs({
        defaultLayout: "index" ,
      })
);
app.set("view engine", "hbs");


app.get('/', (req, res) =>{
    res.render('index.hbs');
});

app.listen(8080, ()=>console.log("Started")); 

感谢您的回复

这是由于 express-handlebars 的默认路径解析。添加 layout: false 以禁用它。

app.get('/', (req, res) =>{
    res.render('index.hbs', {layout: false});
});

defaultLayout: null

app.engine(
      "hbs",
      exphbs({
        defaultLayout: null ,
      })