2012-11-11 6 views
6

以下の例では、プレイヤーの名前のリストを生成します。プレイヤーはMongoDBデータベースのデータセットです。Meteorのコレクションを反復処理中にインデックスを取得する方法はありますか?

<template name="players"> 
    {{#each topScorers}} 
    <div>{{name}}</div> 
    {{/each}} 
</template> 

はしかし、私は行でそれらの4を表示させたい、と4人のプレーヤーが印刷された後、私は<hr />でラインを分割して、続けていきたいです。たとえば、

<template name="players"> 
    {{#each topScorers}} 
    <div style="float:left;">{{name}}</div> 
    {{if index%4==0}} 
     <hr style="clear:both;" /> 
    {{/if} 
    {{/each}} 
</template> 

コレクションを反復処理している間、どうすればいいですか?

答えて

6

ハンドルバーの最新バージョンは@indexフィールドをサポートしていますが、これは流星のバージョンではまだ実装されていません(https://github.com/meteor/meteor/issues/489)。

あなたがあなた自身の{{#each_with_index}}ヘルパーを実装することができます確かに、それは次のようになります。

Handlebars.registerHelper('each_with_index', function(items, options) { 
    var out = ''; 
    for(var i=0, l=items.length; i<l; i++) { 
    var key = 'Branch-' + i; 
    out = out + Spark.labelBranch(key,function(){ 
     options.fn({data: items[i], index: i}); 
    }); 
    } 

    return out; 
}); 

これの欠点は、あなたが反応的に再レン​​ダリングされません流星の{{#each}}ヘルパーのnice値を、失うことです1つのアイテムが変更されたときの全体のリスト

EDIT:おかげでhttps://github.com/meteor/meteor/issues/281#issuecomment-13162687

7

へのポインタのための別の解決策を@zorlak、コレクションの反応性を維持することに沿って、map cursor functionでテンプレートヘルパーを使用することです。ここで

はコレクションとそれぞれを使用した場合、インデックスを返す方法を示す例です:

index.html: 

<template name="print_collection_indices"> 
    {{#each items}} 
    index: {{ this.index }} 
    {{/each}} 
</template> 

index.js: 

Items = new Meteor.Collection('items'); 

Template.print_collection_indices.items = function() { 
    var items = Items.find().map(function(doc, index, cursor) { 
    var i = _.extend(doc, {index: index}); 
    return i; 
    }); 
    return items; 
}; 
関連する問題