2013-07-28 46 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的某處複製它嗎? –

相關問題