【问题标题】:Handelbars complie() function returning undefinedHandlebars compile() 函数返回未定义
【发布时间】:2022-01-03 03:09:56
【问题描述】:

我正在将我的 handelbrake 文件编译为模板,然后使用 puppeteer 生成 pdf,但 hbs.complie() 函数返回未定义。

这里是渲染模板的函数

async function renderTemplate(data, templateName) {
  const filePath = path.join(__dirname, "templates", `${templateName}.hbs`);
  if (!filePath) {
    throw new Error(`Could not find ${templateName}.hbs in generatePDF`);
  }
  console.log(filePath);
  const html = await fs.readFile(filePath, "utf-8");
  return hbs.compile(html)(data);
}

我在 express 中这样使用这个函数:

app.get("/generate-pdf", async (req, res) => {
  const htmlContent = await renderTemplate({ name: "test" }, "test");
  console.log("Content: ", htmlContent);
  await generatePDF("test.pdf", htmlContent);

  res.sendFile(path.join(__dirname, "test.pdf"));
});

我似乎不知道问题是什么,有人可以帮忙。

【问题讨论】:

    标签: node.js express handlebars.js


    【解决方案1】:

    这一行永远是假的,因为它是一个字符串。

    if (!filePath) {
        throw new Error(`Could not find ${templateName}.hbs in generatePDF`);
    }
    

    试试

    if (!fs.existsSync(filePath)) {
        throw new Error(`Could not find ${templateName}.hbs in generatePDF`);
     }
    

    如果这没有引发错误,您很可能在模板中有未定义的参数或无效的语法。

    【讨论】:

    • 它不会抛出任何错误我试过你的方式,但htmlContent 总是未定义。
    • 在编译函数周围放置一个try catch块,将错误记录到控制台,然后检查你的日志
    • no nothing in try catch 我试过了可能是模板错了?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 2020-10-22
    • 2019-01-07
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多