用javascript中的iron路由器动态添加路由

dynamically adding route with iron router in javascript

本文关键字:动态 添加 路由 路由器 iron javascript 中的      更新时间:2023-09-26

我想用iron路由器制作一条路由,但由于某种原因,它根本无法呈现任何内容。

<a target='_blank' href='/strategy?_id=" + strategyId + "'>Details</a>

我的Router.map函数是这样的:

this.route('strategy', {
    path: 'strategy',
    data: function(){
        return Strategies.findOne(this.params._id);
    },
    action:function(){
        this.render();
    }
});

该链接显然正确地链接到

http://localhost:3000/strategy?_id=jShHwfv4fM7oxnrg2

但由于某些原因,它根本没有呈现任何内容(生成的模板为空)。

另外,我试着做了这个:

<a target='_blank' href='" + Router.route('strategy', {_id: strategyId}) + "'>Details</a>

但它实际上立即执行路由。我想要的只是渲染链接。我在这里错过了什么?


编辑以下第一个答案:我知道pathFor,但(也许我的解释不清楚)-你上面看到的锚代码在JS函数(file.JS)中,我说的不是一个可以轻松使用pathFor的html文件。这个锚点是在JS函数中动态生成的。我不能在js函数afaik 中使用手柄代码

要在模板中呈现路由URL,应使用pathFor:

<template name="strategy">
  {{#with strategy}}
    <a  href={{pathFor 'strategy'}} target="_blank">Details</a>
  {{/with}}
</template>

pathFor将路由名称作为参数,并使用当前数据上下文呈现URL,您应该将当前数据上下文设置为URL所依赖的文档。

你的路线定义被破坏了,应该是这样的:

this.route("strategy",{
  // specify the strategy _id as an URL component instead of query parameter
  path:"/strategy/:_id",
  data: function(){
    // this.params._id lookups for URL components, not query params
    var strategy=Strategies.findOne(this.params._id);
    return {
      strategy:strategy
    };
  }
});

正确形成路由的路径很重要:它们总是以/开头,并且可以使用以下语法包含命名参数::parameterName,这些参数可以在使用this.params.parameterName的路由函数中检索。

编辑:

要在JS中获得正确的路径,请使用Router.path,这就是pathFor所使用的:

Template.strategy.helpers({
  anchor:function(strategy){
    var href = Router.path("strategy",strategy);
    return "<a href='"+href+"'>Link</a>";
  }
});

您需要使用三方括号表示法来呈现锚点。

<template name="strategy">
  {{{anchor strategy}}}
</template>