javascript - 使用 HBS 时遇到的问题
问题描述
我是后端的菜鸟,我正在学习 Express 并使用 HBS 作为模板引擎。每次在 Express 中使用 hbs 部分时都会发生这种情况。
代码
const express = require("express");
const app = express();
const hbs = require("hbs");
const path = require("path");
const port = process.env.PORT || 3000;
// public static path
const static_path = path.join(__dirname, "../public");
const templates_path = path.join(__dirname, "../templates/views");
const partials_path = path.join(__dirname, "../templates/partials");
app.set("view engine", "hbs");
app.set("views", templates_path);
hbs.registerPartial(partials_path);
app.use(express.static(static_path));
// routing
app.get("/", (req, res) => {
res.render("index");
});
app.get("/about", (req, res) => {
res.render("about");
});
app.get("/weather", (req, res) => {
res.render("weather");
});
app.get("*", (req, res) => {
res.status(404).render("404error");
});
app.listen(port, () => {
console.log("listning on port " + port);
});
错误
throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined');
^
Error: Attempting to register a partial called "D:\Projects\ExpressWeb\templates\partials" as undefined
at HandlebarsEnvironment.registerPartial (D:\Projects\ExpressWeb\node_modules\handlebars\dist\cjs\handlebars\base.js:80:15)
at Instance.registerPartial (D:\Projects\ExpressWeb\node_modules\hbs\lib\hbs.js:222:35)
at Object.<anonymous> (D:\Projects\ExpressWeb\src\app.js:15:5)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47 {
description: undefined,
fileName: undefined,
lineNumber: undefined,
endLineNumber: undefined,
number: undefined
}
添加这个来增加描述,因为 Stack Overflow 不允许我发布这个,因为我上传的代码比描述更多,而且我不知道要问什么。
解决方案
根据文档,它是 -hbs.registerPartials(partials_path);
不是hbs.registerPartial(partials_path);
推荐阅读
- mysql - MySQL连接表并选择动态行作为列
- oracle - Oracle 12c 在具有外键的表上使用 onDelete 触发器和 onDelete 级联 setNull 抛出 ORA-00600:内部错误代码,参数:[13001]
- react-native - 如何在 react-native 中从我的平面列表中打开 pdf?
- angular - 如何在注入useClass的子服务中使Angular“看到”方法?
- c# - 找不到对称密钥“keyFieldProtection”,因为它不存在或您没有权限。
- google-cloud-ml - "error": "预测失败:未知错误。"
- javascript - 从导出到 excel 中排除隐藏的列名和相应的 colmodel
- ruby-on-rails-5 - 如何找到问题所在的文件
- python - 在 Pandas 中分配 NaN 不粘?
- laravel - throw new InvalidArgumentException("查看 [admin.product.edit_product] 找到。");