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

折月煮酒 提交于 2019-12-25 01:14:08

问题


I ask my probleme here

But after I use the proposed solution I had this error:

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

structure of my code:

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

in index.js i use this code : i add folder layouts in this line of code:

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

All code (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")); 

thanks for your response


回答1:


This is due to express-handlebars's default path resolving. Add layout: false to disable it.

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

Or defaultLayout: null

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


来源:https://stackoverflow.com/questions/59251312/use-multiples-defaultlayout-express-handlebars-in-nodejs-error-enoent-no

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!