Handlebars 不返回任何值,但它存在于 {{this}}
Handlebars returning no value but it exists in {{this}}
使用 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);
});
});
有人有什么想法吗?
谢谢!
如果将 mongoose 模型对象传递给 Handlebars,您可能会遇到问题。
(因为mongoose包装了一个对象,属性加了getters/setters)
要解决此问题,请尝试 运行 您的查询 {lean: true}
或在将其发送到 handlebars 之前致电 modelObj.toObject()
。
使用 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);
});
});
有人有什么想法吗?
谢谢!
如果将 mongoose 模型对象传递给 Handlebars,您可能会遇到问题。 (因为mongoose包装了一个对象,属性加了getters/setters)
要解决此问题,请尝试 运行 您的查询 {lean: true}
或在将其发送到 handlebars 之前致电 modelObj.toObject()
。