【问题标题】:Handlebars returning no value but it exists in {{this}}车把没有返回值,但它存在于 {{this}}
【发布时间】:2017-02-18 05:53:47
【问题描述】:

使用 Handlebars 4.0.6 和 NodeJS 7.4.0,我使用 {{this}} 输出我的模板接收的数据,输出:

{ _id: 58a7de1c7275f8208438ae4a,
  author: 589a12b5a08e0c2f24ece4e8,
  dateCreated: 2017-02-18T05:39:40.650Z,
  section: 58a7d57c9ce34527bce7e041,
  slug: 'this-one-will-work',
  title: 'this one will work',
  color: '#d313ff',
  __v: 0,
  fields: 
  [ { fieldId: 58a3cff51da0ea5d00972804,
      fieldSlug: 'color',
      value: '#d313ff',
      _id: 58a7de1c7275f8208438ae4b } ] }

但是,在 {{this}} 正下方的模板中使用 {{color}}{{this.color}} 不会输出任何内容。

我在 Promise 中使用 mongoose 获取数据,然后编译它,使用 res.send()

这是我的编译函数:

    const Handlebars = require('handlebars');
    const fs = require('fs');
    const path = require('path');

    module.exports = (template, data) =>
      new Promise((resolve, reject) => {
        const templateWithFormat = template.endsWith('.hbs') ? template : `${template}.hbs`;
        const templatePath = path.resolve(__dirname, '..', '..', 'templates', templateWithFormat);

        fs.readFile(templatePath, 'utf-8', (err, file) => {
          if (err) reject(err);

          const compiled = Handlebars.compile(file);
          const html = compiled(data);

          resolve(html);
        });
      });

有人有什么想法吗?

谢谢!

【问题讨论】:

  • 我刚刚尝试运行此代码:jsbin.com/goxufawulo/1/edit?js 并将颜色呈现为“#d313ff”。我使用 Node.js 6.9 和把手 4.0.6。你能提供一段可运行的代码,给你想要的输出吗?
  • 我使用的是 Node 7.4.0 和 Handlebars 4.0.6。我真的没有做太多不在您的 JSBin 中的事情,所以也许它只是 Node 版本?有机会我会尝试不同的版本。
  • 刚刚使用 Node 7.4.0 进行了测试。一些不同的东西导致了这个问题。
  • @AntonioNarkevich 感谢您这样做;我已经用我的环境中的一些代码更新了我的答案
  • 我建议您在编译之前使用console.log(data.color),也可以对模板执行相同的操作(如果读取正确的话)。然后我建议尝试调用 data.toObject() 之前将它传递给编译为 mongoose 包装对象。

标签: node.js handlebars.js templating


【解决方案1】:

如果您将猫鼬模型对象传递给 Handlebars,您可能会遇到问题。 (因为 mongoose 包装了一个对象并为属性添加了 getter/setter)

要解决此问题,请尝试使用{lean: true} 运行您的查询或致电modelObj.toObject(),然后再将其发送到车把。

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 2014-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多