2015-08-10 1 views
1

У меня есть коллекция itemInCollection = new Meteor.Collection('stuff'), и я использую itemInCollection.find(), чтобы получить все предметы в нем. Теперь я перебираю результирующий курсор, чтобы показать атрибут name в шаблоне.Как увеличить и отобразить счетчик переменных с помощью помощника шаблона Meteor?

<head> 
    <title>hello</title> 
</head> 
<body> 
    <h1>Welcome to Meteor!</h1> 
    {{> hello}} 
</body> 

<template name="hello"> 
    <button>Click Me</button> 
    {{#each item}} 
    {{counter}} : {{name}} 
    {{/each}} 
</template> 

Теперь я просто хочу представить число перед именем, например, например.

1. John 
2. Doe 
3. Darling 

Как можно счетчик быть реализован в вспомогательную функцию? Я попытался следующие:

Template.hello.helpers({ 
    'item': function() { 
    return itemInCollection.find(); 
    }, 
'counter': function() { 
    var counter = PrimerList.find().count(), 
     arr = []; 
    for (var i = 0; i < counter; i++) { 
     arr.push(i + 1); 
    } 
    return arr; 
    } 
}); 

и в шаблоне я написал это:

{{#each item}} 
     {{#each counter}} {{this}} {{/each}} : {{name}} 
    {{/each}} 

, но это дало мне нравится:

1 2 3 John 
1 2 3 Doe 
1 2 3 Darling 

ответ

1

Вот как вы можете это сделать:

Template.hello.helpers({ 
    'item': function() { 
     return itemInCollection.find().map(function(document, index) { 
      document.index = index + 1; 
      return document; 
     }); 
    } 
}); 

<template name="hello"> 
    <button>Click Me</button> 
    {{#each item}} 
    {{index}} : {{name}} 
    {{/each}} 
</template> 
0

Вы можете расширить свои пункты в помощнике, как

items: function() { 
    var counter = 0; 
    return itemInCollection.find().map(function (item) { 
     return { 
      name: item.name, 
      counter: counter++ 
     }; 
    }); 
}