2014-10-27 24 views
3

我有一個'profile'模板,我將在其中顯示與用戶相關的內容。所以我想爲模板做一個路由,但是在'path'我想動態插入當前用戶的用戶名。就像我們動態地改變網址關於帖子的ID和一切。 以下是截至目前的路由器代碼塊。如何使用當前用戶的用戶名作爲Iron的路由器參數:router

Router.map(function() { 

    this.route('profile', { 
     path: '/profile', //here instead of 'profile' I wanna dynamically insert the current user's username. 
    }); 
}); 

順便說一下,我能夠將用戶相關數據加載到上述模板。 我嘗試以試錯方式將用戶名(/username)加載到路徑路徑,但徒勞無功。 :(
我想我不是很好用鐵路由器畢竟請幫助

+0

您是否嘗試過使用Router.go,並使用其用戶名重定向到路由? – 2014-10-27 19:13:22

回答

0

你有沒有試過這種

this.route('profile', { 
    path: '/:username', 
    data: function() { return Meteor.user().username; } 
}); 
+0

是的,嘗試了這個和其他許多人,但仍然徒勞無功。不知何故,我無法獲得id或用戶名。 :( – metpb 2014-10-27 20:00:41

+0

@metpb我建議使用mongo指南針它可以幫助你想象問題可能是什麼 – 2018-02-16 00:28:32

0

使用router parameters:?

Router.map(function() { 
    this.route('profile', { 
    path: '/:_username', //dynamic parameter username 
    data: function() { 
     //here you will get the username parameter 
     var username = this.params.username; 
     return { 
     user: Meteor.users.find({ username: username }) //you can use user object in template 
     }; 
    } 
    }); 
}); 
0

不要忘記路線上的waitOn屬性。大多數情況下,這只是關閉時間,爲此創建出版物是擺脫該問題的最佳方式..

服務器端,publications.js

Meteor.publish('me', function() { 
    if(!this.userId) return false; 
    else return Meteor.users.find({_id: this.userId}); 
}); 

在你Router.map()路線之一:

this.route('me', { 
    template: 'profile', 
    notFoundTemplate: 'profile_not_found', 
    path: '/profile', 
    waitOn: function() { 
     return Meteor.subscribe("me"); 
    }, 
    data: function() { 
     return Meteor.user(); 
    } 
}); 

不要忘記這些配置位,以及:

// Router config.. pretty self explanatory 
Router.configure({ 
    layoutTemplate: 'main', 
    notFoundTemplate: 'not_found', 
    loadingTemplate: 'loading' 
}); 
// handle the loading screen 
Router.onBeforeAction('loading'); 
// make sure you define routes here that rely on data to throw back 
// 404/not found equivalent pages. e.g. no search results found, 
// or in this case profile not found 
Router.onBeforeAction('dataNotFound', {only: ['profile']}); 

,你可以使用個人資料模板:

<template name="profile"> 
     Current user Id: {{_id}} 
    </template> 

    <template name="profile_not_found"> 
     Profile not found. Are you logged in? 
    </template> 
1

我也在這一段時間裏苦苦掙扎......然後我碰到了this SO answer。在我的情況下,我做的一切正確,除了沒有通過用戶名連同模板pathFor鏈接助手。

由於某些原因,在鐵路由器路由中使用:_id時,不需要在幫助器pathFor中引用它。這是我混亂的根源,也許是其他人的錯誤。

以下是在用於鐵路由器的路徑使用用戶名的示例代碼:

router.js

this.route('/:username', { 
    name: "dashboard", 
    waitOn: function() { 
     return Meteor.subscribe("allUserData"); 
    }, 
    data: function() { 
     return Meteor.users.findOne(); 
    } 
    }); 

publications.js

Meteor.publish("allUserData", function() { 
    if (this.userId) { 
    return Meteor.users.find(this.userId) 
    } else { 
    this.ready() 
    } 
}) 

頁。 html

<a href="{{pathFor 'dashboard' username=username}}"> 
    User Dashboard 
</a> 

同樣,至少在我的具體情況下,我錯過了上述username=username

相關問題