在Node.js中使用倍数DefaultLayout(表达-手把):(错误:ENOENT:无此类文件或目录)

时间:2019-12-09 14:49:51

标签: node.js express express-handlebars

我问我的问题here

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

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

感谢您的回复

1 个答案:

答案 0 :(得分:0)

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

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

defaultLayout: null

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