Suisse
Suisse

Reputation: 3613

How to pass a session befor routing with iron:router on meteor?

In my post_item.html I got this line:

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

In my router.js:

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

In my post_page.js

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

In my post_page.html

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

What am I doing wrong? How can I pass the ID to the new 'page' and show the result?

Upvotes: 0

Views: 149

Answers (2)

Ronin
Ronin

Reputation: 7980

I'm assuming that you're working on the meteor tutorial using the book 'Discover Meteor'. I faced the same issue, however, I was able to solve it without using session. You don't need any helpers anymore, if you use iron router.

client/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'
    });
});

client/posts/post_item.html

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

as you see, in the router.js the id is parsed from the url. Also, we name the /post/:id route after 'posts.show' and we can get the url from the view referencing that name: {{pathFor route='post.show'}}

Upvotes: 1

FullStack
FullStack

Reputation: 6020

Not sure why you need a session for this, but your route looks wrong. Try the below:

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

Upvotes: 1

Related Questions