I have a route
Router.route('/post/:_id', {
name: 'post',
template: 'post'
});
and a helper
Template.post.helpers({
post: function () {
return Posts.findOne(this._id);
}
});
It wont find the specified post. But I guess I'm getting the id in a wrong way. I've seen some projects where they have used sessions. Is this really necessary? Isn't it possible to get the parameters from the router?
Usually you'd set the data context at the route level like this :
Router.route("/post/:_id",{
name:"post",
template:"post",
waitOn:function(){
return this.subscribe("post",this.params._id);
},
data:function(){
return Posts.findOne(this.params._id);
}
});
In RouteController
methods you can access the URL parameters using this.params.parameterName
.
Then in your post template you can access the data context set by the router without the need of a dedicated helper.
<template name="post">
post id is {{_id}}
</template>
As far as the posts list is concerned, you can stick to the same pattern :
Router.route("/posts",{
name:"posts",
template:"posts",
waitOn:function(){
return this.subscribe("posts");
},
data:function(){
return {
posts:Posts.find()
};
}
});
<template name="posts">
{{#each posts}}
{{> postItem}}
{{/each}}
</template>