我有一個輔助功能正從一個對象的屬性(從計算器樣本轉換)時,做錯誤檢查:{{#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