我试图在我的main.hbs上包含hbs部分但是我得到一个错误,找不到部分内容。这是我在server.js上的代码
const express = require("express");
const hbs = require("hbs");
const port = process.env.PORT || 3000;
var app = express();
hbs.registerPartials(__dirname + "/views/partials");
app.set("view engine", "hbs");
app.use(express.static(__dirname + "/public"));
//
app.get("/",(req, res) => {
res.render("main.hbs");
})
我的文件夹结构如下所示
JS PROJECT
|__views
|__partials
|__htmlfooter.hbs
|__htmlheader.hbs
|__main.hbs
...在main.hbs上我有
{{> htmlheader}}
<h1>test</h1>
{{> htmlfooter}}
当我启动服务器并点击该路由时,我收到错误:
Error: /Users/sansol/Projects/Web_Dev/JS_Project/views/main.hbs: The partial htmlheader could not be found
at Object.invokePartial (/Users/sansol/Projects/Web_Dev/JS_Project/node_modules/hbs/node_modules/handlebars/dist/cjs/handlebars/runtime.js:266:11)
at Object.invokePartialWrapper [as invokePartial] (/Users/sansol/Projects/Web_Dev/JS_Project/node_modules/hbs/node_modules/handlebars/dist/cjs/handlebars/runtime.js:68:39)
at Object.eval [as main] (eval at createFunctionContext (/Users/sansol/Projects/Web_Dev/JS_Project/node_modules/hbs/node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js:254:23), <anonymous>:5:31)
at main (/Users/sansol/Projects/Web_Dev/JS_Project/node_modules/hbs/node_modules/handlebars/dist/cjs/handlebars/runtime.js:173:32)
at ret (/Users/sansol/Projects/Web_Dev/JS_Project/node_modules/hbs/node_modules/handlebars/dist/cjs/handlebars/runtime.js:176:12)
at ret (/Users/sansol/Projects/Web_Dev/JS_Project/node_modules/hbs/node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js:525:21)
at /Users/sansol/Projects/Web_Dev/JS_Project/node_modules/hbs/lib/hbs.js:63:19
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:511:3)
我做错了什么?
由于
答案 0 :(得分:0)
我从我的角度发现了一个愚蠢的错误,但生病了仍然添加答案 我在一个名为server的文件夹中运行server.js文件,当我使用__dirname
时,我正在寻找该文件夹中的部分和公共文件夹要解决我添加的问题
const path = require("path")
并更改了
hbs.registerPartials(path.join(__dirname, "../", "/views/partials"));
app.use(express.static(path.join(__dirname , "../" , "/public")));
答案 1 :(得分:0)
const express = require("express");
const hbs = require("hbs");
const port = process.env.PORT || 3000;
var app = express();
app.set("view engine", "hbs");
app.use(express.static(__dirname + "/public"));
hbs.registerPartials(__dirname + "/views/partials"); // <-- Place "hbs.registerPartials" in here !
您必须在hbs.registerPartials()
之后致电app.set("view engine", "hbs")
!