この質問によると、Handlebars rc1 で次のようなことが可能でした:
{{#each links}}
<li>{{@index}} - {{url}}</li>
{{/each}}
{{@index}}基本的に、反復インデックスを提供します。これは、テーブルを作成するときに非常に役立ちます。
Ember.js rc3 でこれを試すと、予期しないトークン エラーが発生します。これはもう機能しませんか?うまくいきましたか?反復インデックスを取得する別の方法はありますか?
これは、{{index}} でインデックスを取得するのに役立ち、配列の最初または最後のオブジェクトの反復がそれぞれ {{first}} と {{last}} であるかどうかを並べて確認できます。
Ember.Handlebars.registerHelper("foreach", function(path, options) {
var ctx;
var helperName = 'foreach';
if (arguments.length === 4) {
Ember.assert("If you pass more than one argument to the foreach helper, it must be in the form #foreach foo in bar", arguments[1] === "in");
var keywordName = arguments[0];
options = arguments[3];
path = arguments[2];
helperName += ' ' + keywordName + ' in ' + path;
if (path === '') {
path = "this";
}
options.hash.keyword = keywordName;
} else if (arguments.length === 1) {
options = path;
path = 'this';
} else {
helperName += ' ' + path;
}
options.hash.dataSourceBinding = path;
// Set up emptyView as a metamorph with no tag
//options.hash.emptyViewClass = Ember._MetamorphView;
// can't rely on this default behavior when use strict
ctx = this || window;
var len = options.contexts[0][path].length;
options.helperName = options.helperName || helperName;
options.contexts[0][path].map(function(item, index) {
item.index = index;
item.first = index === 0;
item.last = index === len - 1;
})
if (options.data.insideGroup && !options.hash.groupedRows && !options.hash.itemViewClass) {
new GroupedEach(ctx, path, options).render();
} else {
return Ember.Handlebars.helpers.collection.call(ctx, Ember.Handlebars.EachView, options);
}
});
これは次のようにテストできます
{{#foreach array}}
{{log index first last}}
{{/foreach}}
私は最近同じ問題を抱えていました。バインドされたヘルパーを作成し、バインディングを介してそれらのオブジェクトを渡すことで終了します。たとえば、ここのアイテムは ember DS.Store オブジェクトであり、コンテンツはコントローラーの「コンテンツ」です。それを願っています
Ember.Handlebars.registerBoundHelper 'isPair', (content, options)->
item = options.hash.item
content_name = options.hash.content || 'content'
if @get(content_name).indexOf(item) % 2 == 0 then 'is-pair' else 'is-unpair'
そして、あなたの見解では、それを呼び出します
{{isPair content itemBinding='order'}}
それがあなたが探しているものかどうかはわかりませんが、プロジェクトでそれを使用する方法についていくつかのアイデアを与えるかもしれません.
ところで。Ember は #each ヘルパーを上書きするので、@index がないと思います