【问题标题】:Meteor.js - Using pathFor with a "foreign key"Meteor.js - 使用带有“外键”的 pathFor
【发布时间】:2014-04-10 04:21:21
【问题描述】:

我有一个Posts 集合,其中集合中的每个Post 都有一个userId 属性。在我的帖子详细信息页面上,我想使用 pathFor 帮助程序将用户名与指向其个人资料的链接一起包装起来。如果我只包含{{pathFor 'userProfile'}},它会设置与帖子的_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 与我的Post 文档中的userId 字段一起使用,而不是我的Post 文档中的_id 字段?

如果这很重要,我正在使用 Iron-router。

【问题讨论】:

    标签: meteor iron-router


    【解决方案1】:

    我想你会因为关注Iron Router's example route for pathFor 而感到困惑,看起来像这样:

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

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

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

    那么路径中的:userId 对应于您的Post 文档中的userId 字段。

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

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

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

    【讨论】:

    • 我认为他指的是发帖的用户,不一定是当前用户。
    • 原答案已删除,换成更聪明的答案:)
    • 谢谢。像魅力一样工作。
    • 我认为当你需要在用户列表中使用它时,这个解决方案有问题,因为你会得到用户对象,并且会有 _id 而不是像 Posts 对象中的 userId :/建议只是: {{pathFor 'userProfile' _id=userId}}
    【解决方案2】:

    请注意,如果您使用的是 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"}}
    */
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-19
      • 1970-01-01
      • 2020-12-18
      • 2021-04-23
      • 2015-07-06
      • 2013-06-11
      • 1970-01-01
      相关资源
      最近更新 更多