2013-07-28 47 views
3

我遍历在我的模板中的普通数组:如何将任意模板变量传递给handlebar帮助器?

{{#each chapter in chapterList}} 
    <li>{{ chapter }} {{ test chapter }}</li> 
{{/each}} 

chatperList这里,比方说,[1, 2, 3, 4, 5]。我做了一个把手帮手:

Ember.Handlebars.registerHelper('test', function(chapter) { 
    return this.get('list.selectedChapter') == chapter 
    ? 'selected' 
    : ''; 
}); 

但在辅助函数的chapter变量只是字符串“章”。我怎样才能访问实际的变量本身?

回答

2

这看起来像在灰烬(仍然在最新的1.0版)中的错误...你不能一个变量传递给助手的#each内或你: -

TypeError: Object.defineProperty called on non-object 

我刚刚发现使用options.data内容的解决办法,但它意味着你需要引用你传递的对象,如果它是一个#each内(注意“颜色”,而非彩色下文)

模板:

<ul> 
    <li>{{helpme color 'lorry'}}</li> 

{{#each color in model}} 
    <li>{{helpme 'color' 'lorry'}}</li> 
{{/each}} 
</ul> 

助手:

Ember.Handlebars.helper('helpme', function (color, vehicle, opts) { 
    var str = color; 
    if (typeof opts.data.keywords[color] === 'string') { 
     str = opts.data.keywords[color]; 
    } 
    return new Ember.Handlebars.SafeString(str + '_' + vehicle);  
}); 

...看我JSFiddle

编辑:旧版本的余烬使用Ember.Handlebars.registerHelper()代替 Ember.Handlebars.helper()

1

如果你想要一个绑定的帮手,你需要使用Ember.Handlebars.registerBoundHelper,而不是Ember.Handlebars.helper

Ember.Handlebars.helper('test', function(chapter) { 
    return this.get('list.selectedChapter') == chapter ? 'selected' : ''; 
}); 
+0

我得到一个错误:'遗漏的类型错误:对象。 defineProperty在非对象上调用。我认为这是因为'章节'只是一个标量,而不是一个对象。 –

+0

你可以在JSBin的某处复制它吗? –

相关问题