Iron Router / Meteor - Publish information with username in url
I am relatively new to Meteor (especially Iron Router) and am stuck with the next release ...
I have a route that displays the details of a single post:
this.route('singlePost',{
path:'/posts/:_id',
data:function(){
return Posts.findOne(this.params._id);
}
});
This works great, but I would like to show the username for the owner of the post in the url, not the static path "/ posts /" like:
this.route('singlePost',{
path:'/:username/:_id',
data:function(){
return Posts.findOne(this.params._id);
}
});
The post object includes the owner's user ID but not the username (the username is in the Meteor.users collection).
When I try to set a route with two dynamic values (username, post Id), the pathFor link disappears (I assume because it cannot find the "username" in the returned post object).
How can I get the route to recognize the username? I am guessing some search functionality for the Users collection, but I'm not sure when / where. Also, how can I check the route to make sure the message belongs to the correct username?
Edit - here is the code:
router.js
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading',
waitOn:function(){
return Meteor.subscribe('posts') && Meteor.subscribe('users');
}
});
Router.map(function() {
this.route('home', {
path: '/',
data:function(){
Session.set('pageView','list');
return Posts.find();
}
});
this.route('singlePost',{
path:'/:username/:_id',
data:function(){
Session.set('pageView','single');
return Posts.findOne(this.params._id);
}
});
});
Router.onBeforeAction('loading');
home.html
<template name="home">
{{> postsList}}
</template>
posts_list.html
<template name="postsList">
<ul>
{{#each posts}}
{{> postBlock}}
{{/each}}
</ul>
</template>
single_post.html
<template name="singlePost">
{{> postBlock}}
</template>
post_block.html
<template name="postBlock">
{{#if pageView "list"}}
<li>
<a href="{{pathFor 'singlePost'}}">{{title}}</a><br/>
Author: {{username}}
</li>
{{/if}}
{{#if pageView "single"}}
<h1>{{title}}</h1>
<p>{{description}}</p>
<p>Author: {{username}}</p>
{{/if}}
</template>
post_block.js
Template.postBlock.helpers({
username:function(){
var user = getUserInfo(this.owner);
return user.username;
},
pageView:function(type){
return Session.get('pageView') == type;
}
});
functions.js
getUserInfo = function(id){
return Meteor.users.findOne(id);
}
The username is displayed correctly in both list and detail views, however I am unable to get the path reference for the username reference.
source to share