Javascript 如何使用Meteor模板帮助器递增和显示变量计数器?
我得到了一个Javascript 如何使用Meteor模板帮助器递增和显示变量计数器?,javascript,meteor,spacebars,meteor-helper,Javascript,Meteor,Spacebars,Meteor Helper,我得到了一个itemInCollection=newmeteor.Collection('stuff')Collection,我使用itemInCollection.find()获取其中的所有项目。现在,我迭代生成的光标,以显示模板中的name属性 <head> <title>hello</title> </head> <body> <h1>Welcome to Meteor!</h1> {{>
itemInCollection=newmeteor.Collection('stuff')
Collection,我使用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>
如何在helper函数中实现计数器?我尝试了以下方法:
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;
}
});
但这让我觉得:
1 2 3 John
1 2 3 Doe
1 2 3 Darling
您可以在helper中扩展项目,如
items: function () {
var counter = 0;
return itemInCollection.find().map(function ( item ) {
return {
name: item.name,
counter: counter++
};
});
}
以下是如何做到这一点:
Template.hello.helpers({
'item': function() {
return itemInCollection.find().map(function(document, index) {
document.index = index + 1;
return document;
});
}
});
点击我
{{{#每项}
{{index}}:{{name}
{{/每个}}
items: function () {
var counter = 0;
return itemInCollection.find().map(function ( item ) {
return {
name: item.name,
counter: counter++
};
});
}
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>