MeteorJS + Iron-Router:如何使用pathFor调用集合中的下一个项目?
在发布此问题之前,我做了很多研究,但找不到答案.我敢肯定这是一个简单的任务,但是由于某种原因,它使我头疼.
I did a lot of research before posting this question and couldn't find the answer. I'm sure it's a simple task, but it's going over my head for some reason.
我有一个帖子"类型页面,其中列出了我的收藏中的所有项目,还有一个单个帖子"页面,用于显示所选帖子的内容.我有两个分页箭头可以转到上一个项目和下一个项目.如何获取上一个/下一个帖子的URL并将其显示在我的模板中?
I have a "posts" type page that lists all items in my collection, and a "single post" page to display the contents of the selected post. I have two pagination arrows for going to the previous item and next item. How can I grab the URL for the previous/next posts and display it in my template?
任何帮助将不胜感激,谢谢!
Any help would be appreciated, thanks!
我创建了示例应用程序,该应用程序完全可以满足您的需求. 请检查它: https://github.com/parhelium/meteor -so-post-next-prev/tree/master
I created sample application which exactly do what you need. Please check it : https://github.com/parhelium/meteor-so-post-next-prev/tree/master
简要说明此代码的重要部分(请参见 repo 查找更多详细信息):
Briefly explanation of important parts of this code ( see repo to find more details ):
首先,您需要一些模型:
First you need to have some model:
{title:"1 post", createdAt:moment("01-10-1995", "DD-MM-YYYY").toDate()}
并发布功能:
Meteor.publish("postDetailsNext",function(postId){ });
Meteor.publish("postDetailsPrev",function(postId){ });
Meteor.publish("postDetails",function(postId){});
棘手"部分是如何编写查询以获取next
和prev
帖子的信息.
The 'tricky' part is how to write queries for taking next
and prev
posts.
Meteor.publish("postDetailsNext",function(postId){
// load post object which should be displayed in 'postDetails' route
var post = Posts.findOne({_id:postId});
// find one post from sorted cursor which is older than main post
return Posts.find({createdAt:{$gt:post.createdAt}},{sort:{createdAt:1}, limit:1})
});
以及类似的内容:
Meteor.publish("postDetailsPrev",function(postId){
var post = Posts.findOne({_id:postId});
return Posts.find({createdAt:{$lt:post.createdAt}},{sort:{createdAt:-1}, limit:1})
});
请注意,来自以上发布功能的查询在sort field
中有所不同.
Note that queries from above publish functions differs in sort field
.
this.route('postDetails',{
where:'client',
path:'/post/:_postId',
template:'postDetails',
waitOn:function(){
return [
Meteor.subscribe('postDetails', this.params._postId),
Meteor.subscribe('postDetailsPrev', this.params._postId),
Meteor.subscribe('postDetailsNext', this.params._postId)
]
},
data:function(){
var post = Posts.findOne({_id:this.params._postId});
if(post == null) return {};
else
return {
post : Posts.findOne({_id:post._id}, {limit:1}),
prev : Posts.findOne({createdAt:{$lt:post.createdAt}},{sort:{createdAt:-1}}),
next : Posts.findOne({createdAt:{$gt:post.createdAt}},{sort:{createdAt:1}})
}
}
}
})