Get parameters from router using Meteor and iron: router
I have a route
Router.route('/post/:_id', {
name: 'post',
template: 'post'
});
and auxiliary
Template.post.helpers({
post: function () {
return Posts.findOne(this._id);
}
});
It will not find the specified post. But I think I am wrong. I've seen some projects where they used sessions. Is it really necessary? Can't get parameters from router?
source to share
Typically, you 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 URL parameters with this.params.parameterName
.
Then, in your message template, you can access the data context set by the router without the need for a dedicated helper.
<template name="post">
post id is {{_id}}
</template>
As for the list of posts, you can follow 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>
source to share
More organized to have all your data extract points in helpers. So, you can do this:
routes.js
Router.route('/post/:_id', {
name: 'post',
template: 'post'
});
post.js
Template.post.helpers({
post: function() {
var postId = Router.current().params._id;
return Posts.findOne({_id: postId});
}
});
Remember, if you don't subscribe (messages) to any other file, you can subscribe to the router itself:
routes.js (with subscription)
Router.route('/post/:_id', {
name: 'post',
template: 'post',
waitOn: function() {
return Meteor.subscribe('posts');
}
});
Update:
Router.current().params._id
seems to have a problem, it will return all IDs of that route that were previously executed.
So the restructured way should be (example from my app):
route.js
Router.route('/play/:gameId', {
name: 'play',
template: 'gamesPlay',
waitOn: function() {
return Meteor.subscribe('games');
},
onBeforeAction: function() {
Session.set('gameId', this.params.gameId);
console.log('game id set '+Session.get('gameId'));
this.next();
},
onStop: function() {
// do something when user navigate away from this route
}
});
games.js
Template.gamesPlay.helpers({
game: function() {
var gameId = Session.get('gameId'); //instead of Router.current().params.gameId;
var game = Games.findOne({_id: gameId});
return game;
}
});
source to share