2015-07-10 67 views
0

在我post_item.html我得到這一行:如何通過一個會話befor路由與鐵:流星路由器?

<a href="{{pathFor 'postPage' _id=this._id}}" class="discuss btn">Discuss</a> 

在我router.js:

Router.map(function() { 
    this.route('postPage',{path:'/posts/:_id', 
    beforeRoutingTo: function(id) { 
     console.log("hello!"); 
     Session.set('currentPostId', id); 
    } 
    }); 
    }); 

在我post_page.js

Template.postPage.helpers({ 
    currentPost: function() { 
    return Posts.findOne(Session.get('currentPostId')); 
    } 
}); 

在我post_page.html

<template name="postPage"> 
{{#with currentPost}} 
{{> postItem}} 
{{/with}} 
</template> 

我做錯了什麼? 如何將ID傳遞到新的「頁面」並顯示結果?

回答

1

我假設你正在使用本書'Discover Meteor'開發流星教程。然而,我面臨同樣的問題,我無需使用會話即可解決問題。如果您使用iron router,則不再需要任何助手。

客戶端/ router.js:

Router.map(function() { 
    this.route('/post/:_id', function() { 
     var item = Posts.findOne({_id: this.params._id}); 
     this.render('postItem', {data: item}); 
    }, 
    { 
     name: 'post.show' 
    }); 
}); 

客戶端/職位/ post_item.html

<a href="{{pathFor route='post.show'}}" class="discuss btn">Discuss</a> 

如你所見,在router.js的ID從URL解析。此外,我們將其命名「posts.show」/post/:id路線,我們可以從引用該名稱的看法得到的網址:{{pathFor route='post.show'}}

+0

WOW!那真的有用!我嘗試了很長一段時間很多不同的類型... 我想這樣做更多,但它不工作: 'Router.route('/ post /:_ id',{ name:'postPage' , 數據:功能(){ 返回 Posts.findOne(this.params._id);} });' 在post_item.html: ''Discuss 而在post_page.html '<模板名稱=「postPage」>

{{> postItem}}
' – Suisse

+0

只是在這種情況下,我想顯示更多的只是項目,我需要post_pa ge.html用於向該單擊的項目添加更多詳細信息。 我只有老書「發現流星」 - 我看到了這本書的版本(用德語) - http://de.discovermeteor.com/chapters/routing/ – Suisse

+0

OK thx!我測試了一下你的代碼並將其改爲: route.js: 'this.route('/ post /:_ id',function(){ var item = Posts.findOne({_ id:this.params ._id}); this.render( 'postPage',{數據:項});} , { 名: 'postPage' });' 在post_item。HTML的討論鏈接: ''Discuss在 我post_page.html可以添加更多的詳細信息: '<模板名稱= 「postPage」>

{{> postItem}} mooore details goes here! thx Ronin!
' – Suisse

1

不知道爲什麼你需要這個會話,但你的路線看起來不對。嘗試下面的方法:

Router.map(function() { 
    this.route('postPage',{path:'/posts/:_id', 
    onBeforeAction: function() { 
     console.log("hello!"); 
     Session.set('currentPostId', this.params._id); 
    } 
    }); 
}); 
+0

這是'this.params._id' – fuzzybabybunny

+1

感謝。更新了 – FullStack