4

我有一个Posts集合,集合中的每个Post集合都有一个userId属性。在我的帖子详细信息页面上,我想使用pathFor帮助程序将用户名与指向其个人资料的链接一起包装起来。如果我只是 inlcude {{pathFor 'userProfile'}},它会设置与 Post 的链接_id,正如人们所期望的那样,但我显然需要链接中的 userId。

我已经尝试像这样在模板的帮助器上创建第二个数据上下文,但这也不起作用。

脚本:

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

模板:

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

我将如何使用我的文档中的字段,而不是我的pathFor文档中的字段?userIdPost_idPost

如果这很重要,我正在使用铁路由器。

4

2 回答 2

1

我假设您会感到困惑,因为您正在遵循Iron Router 的示例路由pathFor,它看起来像这样:

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

这里的关键是:_id可以是任何字段。因此,对于您的代码,请尝试:

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

然后:userId路径中的 对应于文档中的userId字段。Post

您也不需要模板助手或#with块。您现在的模板只是:

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

并且userProfile路由会发送整个Post文档及其所有属性,包括文档_iduserIdauthor以及任何其他定义的内容。路线知道该选择什么,因为您已经告诉了它:userId,而不是:_id:author或其他什么。

于 2013-12-11T02:21:58.553 回答
1

请注意,如果您使用的是 iron-router 0.8.0,您的 pathFor 标记应该是:

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

根据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"}}
*/
于 2014-04-09T20:21:21.700 回答