Никола Дашић Никола Дашић - 16 days ago 6
Javascript Question

Meteor: Router with URL of a userName?

I have problems with creating routes with user's usernames. So idea is something like this: Click on path and go to that users profile. His link should be something like : http://www.something.com/usersUsername
I was reading and trying everything I found on internet about this but lot of stuff changed so I couldn't manage this.
Only thing I found usefull is that when page loads client ,,watch" paths first and then subscribes to a collection so I got ,,null" for path. Any help? My idea is to create something to waitOn for subscribe...

Packages: iron:router , accounts-ui , accounts-password

Here is code:

Start page, template:

<template name="početna">
<h1>Dobrodošli!</h1>
<h3>Registrujte se:</h3>
{{> register}}
<h3>Prijavite se:</h3>
{{> login}}

{{#if currentUser}}
<h2>Logovan si!</h2>
{{> logout}}
<a href="{{pathFor route='profil' username=username }}">Profil</a>
{{/if}}




Router JS file:

Router.configure({
layoutTemplate: 'okvir'
});

// * * * * * * //

Router.route('/', {
name: 'početna',
template: 'početna',
});

Router.route('/:username', {
waitOn: function(){
return Meteor.subscribe('userData'), Meteor.user().username
},
name: 'profil',
template: 'profil',

});


Simple HTML template file only to se if it works:

<template name="profil">
<h1>RADI</h1>
</template>


Thanks!

Answer

Here you go:

Router.route('/:username',{
    name: 'profil',
    waitOn: function () {
        return Meteor.subscribe('userData', this.params.username)
    },

    action: function () {
        this.render('profil', {
            data: function () {
                return Meteor.users.findOne({username: this.params.username});
            }
        });
    }
});

EDIT:

With this.params.username will let anybody visit that profile, user or not. If you want to prevent that, you can use onBeforeAction()

onBeforeAction: function() {
    if(Meteor.user() && this.params.username == Meteor.user().username){
        this.next();
    } else {
        Router.go('/not-authorized') //or any other route
    }
},