Craig M
Craig M

Reputation: 5628

Meteor.js - Using pathFor with a "foreign key"

I have a Posts collection where each Post in the collection has a userId property. On my post detail page, I want to wrap the user's name with a link to their profile using the pathFor helper. If I just inlcude {{pathFor 'userProfile'}}, it sets up the link with the Post's _id, as one would expect, but I obviously need the userId in the link.

I've tried creating a second data context on the template's helper like so, but this didn't work either.

Script:

Template.postPage.helpers({
    user: function () {
        return {_id: this.userId};
    }      
});

Template:

<template name="postPage">
    {{#with user}}<a href="{{pathFor 'userProfile'}}">{{/with}}{{author}}</a>
</template>

How would I go about using pathFor with the userId field from my Post doc, instead of the _id field from my Post doc?

I'm using iron-router if that matters.

Upvotes: 4

Views: 901

Answers (2)

m2web
m2web

Reputation: 737

Note that if you are using iron-router 0.8.0 your pathFor markup should be:

<template name="postPage">
  <a href="{{pathFor 'userProfile' params=this}}">{{author}}</a>
</template>

Per https://github.com/EventedMind/iron-router/blob/master/lib/client/ui/helpers.js#L42:

/**
 * Example Use:
 *
 *  {{pathFor 'items' params=this}}
 *  {{pathFor 'items' id=5 query="view=all" hash="somehash"}}
 *  {{pathFor route='items' id=5 query="view=all" hash="somehash"}}
*/

Upvotes: 1

Geoffrey Booth
Geoffrey Booth

Reputation: 7366

I assume you're getting flummoxed because you're following Iron Router's example route for pathFor, which looks like this:

Router.map(function () {
  this.route('postShow', {
    path: '/posts/:_id'
  });
});

The key here is that :_id can be any field. So for your code, try:

Router.map(function () {
  this.route('userProfile', {
    path: '/users/:userId'
  });
});

Then the :userId in the path corresponds to the userId field in your Post document.

You also don't need the template helper or the #with block. Your template now is just:

<template name="postPage">
  <a href="{{pathFor 'userProfile'}}">{{author}}</a>
</template>

And the userProfile route is sent the entire Post document with all its properties, both the document _id and the userId, and author and whatever else is defined. The route knows what to choose because you've told it :userId and not :_id or :author or something else.

Upvotes: 1

Related Questions