问题
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