[英]How Do I Increment and Display Variable Counter Using Meteor Template Helper?
我有一個itemInCollection = new Meteor.Collection('stuff')
集合,並且我使用itemInCollection.find()
來獲取其中的所有項目。 現在,我遍歷結果光標以在模板中顯示name
屬性。
<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
這是您可以執行的操作:
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>
您可以在輔助程序中擴展項目,例如
items: function () {
var counter = 0;
return itemInCollection.find().map(function ( item ) {
return {
name: item.name,
counter: counter++
};
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.