2012-11-11 2 views
6

아래 예제는 플레이어의 이름리스트를 생성합니다. 플레이어는 MongoDB 데이터베이스의 데이터 세트입니다.Meteor에서 컬렉션을 반복하면서 인덱스를 가져 오는 방법이 있습니까?

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

는 그러나, 나는 행에 그들 중 네를 표시하려면, 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}} 도우미의 쾌적, 리액턴스를 다시 렌더링하지 않습니다 잃게되는이의 단점을 단일 항목이 변경되면 전체 목록입니다.

편집 : 감사 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; 
}; 
:

여기 컬렉션 각각을 사용하는 경우의 인덱스를 반환하는 방법을 나타내는 일례의

관련 문제