2013-02-13 63 views

回答

59

有一個在示例的語法錯誤。正確的語法是{{@../index}}

我們正在研究如何在未來版本的語言中支持這些參數的自定義命名,以便更輕鬆地處理。 https://github.com/wycats/handlebars.js/issues/907

+1

標記正確的答案雖然有幫助,但這是問題的正確答案。 – 2014-11-19 00:53:16

+0

哦看起來像這是第一個實際的答案,我的不好 – 2016-01-29 02:07:52

+1

這不適用於燼v2.2.0。 @安德魯玩具有正確的答案。 – 2016-02-08 21:10:22

26

這爲我工作:

{{#each company}} 
{{setIndex @index}} 
{{#each employee}} 
    {{../index}} 
{{/each}} 
{{/each}} 

JS:

Handlebars.registerHelper('setIndex', function(value){ 
    this.index = Number(value + 1); //I needed human readable index, not zero based 
}); 

只要確保company對象不具有index屬性。

+1

可悲的是這似乎不一樣,如果內循環從模板渲染工作:''{{>我的模板}}''產量''無法讀取undefined''的特性「指數」。你知道這個解決方案嗎? – Lincoln 2013-04-24 12:09:17

+1

@Lincoln你可以嘗試這裏的建議http://stackoverflow.com/a/18026063/271442 - 我去了包括幫助者的方法。 – mynameistechno 2014-01-29 16:33:40

+0

這是一個了不起的伎倆。我將分享一個jsfiddle鏈接。謝謝! – 2014-05-09 17:42:36

0

registe一個Helper方法:

Handlebars.registerHelper('eachWithIndex', function(cursor, options) { 
    var fn = options.fn, inverse = options.inverse; 
    var ret = ""; 
    var idx = -1; 
    //console.log(cursor); 
    cursor.forEach(function(item){ 
     idx++; 
     console.log(item.index); 
     item.index = idx; 
     ret+=fn(item); 
    }); 
    return ret; 
}); 

車把模板:

{{#eachWithIndex outer}} 
    {{#each inner}} 
    {{../index}} // access outer index like this. I used hanlebars V1.3.0 
    {{index}} // access inner index 
    {{/each}} 
{{/eachWithIndex}} 
7

答案:{{@../index}}

Handlebars docs(見 '各自' 助手部的底部):

「嵌套each塊可以經由depted路徑訪問互爲作用變量要訪問。父索引,例如,可以使用{{@../index}}。「

注意:我使用的是v1.3,因此它至少已經過時了。

提示:助手是你最後的最佳選擇。 9/10有一個更好的解決方案。

+0

這是實際的答案 – 2016-01-29 02:07:10

+0

{{@key}}是否也支持舊版本? – ajayv 2017-01-11 20:31:26

3

它看起來像Ember v2.2.0中有一個新的語法。我在這裏嘗試了所有的答案,但他們不適合我。

我發現的工作是命名父循環的索引和子循環的索引。

{{#each parents as |parent parentIndex|}} 
    {{parentIndex}} 
    {{#each children as |child childIndex|}} 
     {{parentIndex}} 
     {{childIndex}} 
    {{/each}} 
{{/each}}