我有一个辅助功能正从一个对象的属性(从计算器样本转换)时,做错误检查:{{#if}}是否会影响上下文?
module.exports.register = function (Handlebars, options) {
Handlebars.registerHelper('get', function (obj, prop, context) {
if (typeof obj !== 'object') {
throw new Error('get: Cannot get from ' + typeof obj);
}
if (typeof prop !== 'string') {
throw new Error('get: Property must be a string. Type ' + typeof prop + ' not supported');
}
if (!obj.hasOwnProperty(prop)) {
throw new Error('get: Object does not contain the property "' + prop + '"');
}
return obj[prop];
});
}
当我使用这通常只是正常工作:
<div>
{{get ../site.sectionNames tag}}
</div>
...但是,如果我把它放在一个{{#if true}}
元素中,然后obj
未定义:
<div>
{{#if true}}
{{get ../site.sectionNames tag}}
{{/if}}
</div>
我的印象是{{#if}}
doesn't change the context。 这是怎么发生的?
这似乎是预期的行为:https://github.com/wycats/handlebars。 JS /问题/ 196。 – 2015-04-10 21:52:05
谢谢,我添加了一条评论,看看我能否弄清楚为什么会发生这种情况。似乎直接与文档冲突... – jt000 2015-04-11 14:01:28