在Node.js中使用倍数DefaultLayout(表达式-手把):(错误:ENOENT:无此类文件或目录) [英] Use multiples DefaultLayout (express-handlebars) in Nodejs: ( Error: ENOENT: no such file or directory )
本文介绍了在Node.js中使用倍数DefaultLayout(表达式-手把):(错误:ENOENT:无此类文件或目录)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在此处
但是在使用建议的解决方案之后,我出现了以下错误:
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
我的代码的结构:
views/
themes
theme1
layouts/
index.hbs
content1.hbs
theme2
layouts/
index.hbs
content2.hbs
index.js
在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);
所有代码(index.js):
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"));
感谢您的回复
推荐答案
这是由于express-handlebars
的默认路径解析引起的.添加layout: false
将其禁用.
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});
});
或defaultLayout: null
app.engine(
"hbs",
exphbs({
defaultLayout: null ,
})
这篇关于在Node.js中使用倍数DefaultLayout(表达式-手把):(错误:ENOENT:无此类文件或目录)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文