Meteor:如何在模板中获取iron-router参数

Ram*_*san 4 javascript handlebars.js meteor iron-router

如何获取模板中的路由参数值?

路由器

Router.map(function() {
  this.route('userpost', {path: '/mypost/:_id'});
  this.route('usercomment', {path: '/mycomments/:_id'});
});
Run Code Online (Sandbox Code Playgroud)

我当前的位置是localhost:3000/mypost/12345. 我想从路由参数分配路径参数

模板

<template name="mytemplate">
    <a class="tab-item" href="{{pathFor 'userpost' _id=???}}">Post</a>
    <a class="tab-item" href="{{pathFor 'usercomment' _id=???}}">Comment</a>
</template>
Run Code Online (Sandbox Code Playgroud)

sai*_*unt 5

{{pathFor}}使用当前数据上下文将 URL 参数替换为实际值,因此您需要将调用包含在{{#with}}块助手内。

<template name="mytemplate">
  {{#with context}}
    <a class="tab-item" href="{{pathFor "userpost"}}">Post</a>
    <a class="tab-item" href="{{pathFor "usercomment"}}">Comment</a>
  {{/with}}
</template>
Run Code Online (Sandbox Code Playgroud)

context是一个返回具有 的对象的帮助器_id,并且此属性将用于填充计算路径。

Template.mytemplate.helpers({
  context: function(){
    return {
      _id: Router.current().params._id
    };
  }
});
Run Code Online (Sandbox Code Playgroud)