Meteor.js-将pathFor与一个;外键“;
我有一个Meteor.js-将pathFor与一个;外键“;,meteor,iron-router,Meteor,Iron Router,我有一个Posts集合,其中集合中的每个Post都有一个userId属性。在我的帖子详细信息页面上,我想使用pathForhelper将用户名包装为指向其个人资料的链接。如果我只是输入{{pathFor'userProfile'},它会像人们所期望的那样设置带有帖子的\u id的链接,但我显然需要链接中的userId 我尝试过在模板的帮助器上创建第二个数据上下文,就像这样,但这也不起作用 脚本: Template.postPage.helpers({ user: function ()
Posts
集合,其中集合中的每个Post
都有一个userId
属性。在我的帖子详细信息页面上,我想使用pathFor
helper将用户名包装为指向其个人资料的链接。如果我只是输入{{pathFor'userProfile'}
,它会像人们所期望的那样设置带有帖子的\u id
的链接,但我显然需要链接中的userId
我尝试过在模板的帮助器上创建第二个数据上下文,就像这样,但这也不起作用
脚本:
Template.postPage.helpers({
user: function () {
return {_id: this.userId};
}
});
模板:
<template name="postPage">
{{#with user}}<a href="{{pathFor 'userProfile'}}">{{/with}}{{author}}</a>
</template>
{{#与用户}}
如何使用我的Post
文档中的userId
字段而不是我的Post
文档中的\u id
字段来使用pathFor
如果这很重要的话,我会使用铁制路由器。我想你会感到困惑,因为你在跟踪,看起来是这样的:
Router.map(function () {
this.route('postShow', {
path: '/posts/:_id'
});
});
这里的关键是:_id
可以是任何字段。因此,对于您的代码,请尝试:
Router.map(function () {
this.route('userProfile', {
path: '/users/:userId'
});
});
然后路径中的:userId
对应于Post
文档中的userId
字段
您也不需要模板助手或带有块的#。您的模板现在只是:
<template name="postPage">
<a href="{{pathFor 'userProfile'}}">{{author}}</a>
</template>
而userProfile
路由将发送整个Post
文档及其所有属性,包括文档\u id
和userId
,以及author
和定义的任何其他属性。路由知道要选择什么,因为您已经告诉它:userId
,而不是:\u id
或:author
或其他内容。请注意,如果您使用的是iron router 0.8.0,则标记路径应该是:
<template name="postPage">
<a href="{{pathFor 'userProfile' params=this}}">{{author}}</a>
</template>
我想他说的是任何用户发的帖子,不一定是当前用户。原始答案被删除,替换为更聪明的答案:)谢谢。我认为当你需要在用户列表中使用它时,这个解决方案会有问题,因为在那里你会得到用户对象,并且会有_id而不是像Posts对象中那样的userId:/会建议:{{{pathFor'userProfile'\u id=userId}}
/**
* 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"}}
*/