【问题标题】:Regex routing with Iron-router使用 Iron-router 的正则表达式路由
【发布时间】:2015-01-06 19:21:42
【问题描述】:

我正在尝试使用 iron-router 为流星编写一条路由来捕获所有请求:

  • /game/Quarterfinal3
  • /game/Semifinal5
  • /game/Grandfinal1

等等。 这是我尝试过的,但它不起作用......

Router.route('final', {path: "(\\/)(game)(\\/).*?(final)(\\d)"}, function() {
  console.log("final");
  this.render('notStartedGame');
});

我该如何解决这个问题?

【问题讨论】:

  • 请原谅任何错误,因为我也从未使用过流星,也没有使用过铁路由器,但根据他们的文档:Iron Router now uses path-to-regexp 所以,在path-to-regexp 文档中,您可以使用类似/:game/.*(final)\d+.. 的东西盲目射击。
  • 加我的 2 美分:Router.route 的新语法将路径作为第一个参数,您可以选择提供name 选项,这与之前的行为相反。

标签: javascript regex meteor routes iron-router


【解决方案1】:

只要在路径上使用:pathParam 格式,路径中就不需要正则表达式,它将在this.params.pathParam 中可用,即:

如果你想赶上这三个路线:

Router.route('/game/:gameName', function() {
  var acceptablePaths = ["Quarterfinal3", "Semifinal5", "Grandfinal1"],
      gameName = this.params.gameName;
  // check if the game name is one of those that we are looking for
  if ( _.contains(acceptablePath, gameName) ) this.render("notStartedGame");
  // otherwise render a not found template or if you want do something else
  this.render("gameNotFound"); //assuming you have such a template
});

或者如果您正在寻找任何包含“final”的路线:

Router.route('/game/:gameName', function() {
  var checkFor = "final",
      gameName = this.params.gameName;
  // check if the game name includes "final"
  if ( gameName.indexOf(checkFor) > -1 ) this.render("notStartedGame");
  // otherwise render a not found template or if you want do something else
  this.render("gameNotFound"); //assuming you have such a template
});

【讨论】:

  • 效果很好!使用 else 部分根据 /game/:id 的给定游戏 ID 渲染不同的游戏 :) 非常感谢!
【解决方案2】:

为了将来参考(因为 Meteor 可以完全按照您的要求做),DontVoteMeDown comment 就在现场。

下面的路由有一个固定的部分/game,后跟一个基于正则表达式.*final\d+的命名参数/:gameName

Router.route('/game/:gameName(.*final\\d+)', function() {
      console.log(this.params.gameName);
})

注意事项:

  • 您不必在整个路径上使用一个 regex。您可以使用多个与固定部分交织在一起的本地化正则表达式,例如:/fix1/(.*)/fix2/:reg2(.*)/。查看非常漂亮的path-to-regexp documentation

  • 您不必担心不适合 regex 的路径 - 它们根本不会被路由到这里。

  • 记得正确转义你的正则表达式(例如注意双反斜杠)

【讨论】:

    猜你喜欢
    • 2014-10-30
    • 1970-01-01
    • 2020-10-10
    • 2019-01-01
    • 2014-04-14
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多