2012-11-11 40 views
6

下面的例子會生成一個玩家名字列表,其中玩家是來自MongoDB數據庫的數據集。有沒有辦法在遍歷Meteor中的集合時獲取索引?

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

不過,我想在一行中顯示他們四人,並打印四名球員後,我想<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}}幫手正派,不被動地重新呈現整個列表單個項目更改時。

編輯:感謝@zorlak爲指針https://github.com/meteor/meteor/issues/281#issuecomment-13162687

7

另一種解決方案,在保持集合的反應線,是使用模板助手與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; 
}; 
相關問題