我为小型Meteor应用定义了以下路线:
this.route('browse-class', {
path: '/browse/:_class',
data: {
theClass: function() { return this.params._class; },
numBooks: function() { return Books.find({"class": this.params._class},{sort:{"createdAt": 1}}).count(); },
books: function() { return Books.find({"class": this.params._class},{sort:{"createdAt": 1}}); }
}
});
我没有得到的是如何访问数据的返回值。即numBooks。它应该返回一个整数,但我似乎无法使其与模板帮助器中的以下代码配合使用:
Template.browseClass.helpers({
booksFound: function() {
return this.data.numBooks > 0;
},
theOwner: function() {
theUser = Meteor.users.findOne({_id: this.owner});
return theUser.username;
}
});
当我console.log()我正在比较的值时,似乎它正在尝试比较函数而不是它返回的值或其他东西?我有点困惑。
任何想法将不胜感激。谢谢!
最佳答案
应该将数据定义为路由中的函数,如下所示:
data:function(){
var booksCursor=Books.find(...);
return {
theClass:this.params._class,
numBooks:booksCursor.count(),
books:booksCursor
};
}
然后,如果您将
browseClass
指定为路由模板,则将data()
的结果作为数据上下文进行呈现,因此您可以访问如下属性:Template.browseClass.helpers({
booksFound:function(){
return this.numBooks>0;
}
});
<template name="browseClass">
Number of books : {{numBooks}}
{{#each books}}
{{...}}
{{/each}}
</template>