首页 > 解决方案 > 使用 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 不允许我发布这个,因为我上传的代码比描述更多,而且我不知道要问什么。

标签: javascriptnode.jsexpressmustache

解决方案


根据文档,它是 -hbs.registerPartials(partials_path); 不是hbs.registerPartial(partials_path);


推荐阅读