在Iron Router中带有默认路由的动态段

Dynamic segments with default routes in Iron Router?

本文关键字:路由 动态 默认 Iron Router      更新时间:2023-09-26

在Meteor中,使用铁路由器,我试图实现一个路由映射,它有一个动态段和一个回退路由,如果动态段不匹配集合中的任何项目。例如,假设我有一个这样的URL:

http://foobar.com/harold

我想首先检查harold是否匹配Posts集合中的任何id。如果有匹配,那么它应该带我到postPage模板。

如果没有匹配,那么路由器应该呈现harold匹配的任何项。

我已经搜索了所有的铁路由器文档,但似乎找不到正确的方法。我想知道是否有像this.next()这样的东西取消当前的路由映射并进入下一个路由映射。下面是我的尝试:

Router.map(function () {
  this.route('postPage', {
    // matches: '/MFLS6aKqqRZ2JGz9q'
    // matches: '/81zBqGE85aAfjk1js'
    path: '/:postId',
    before: function () {
      //check if segment matches a post ID
      post = Posts.findOne(this.params.postId);
      if (!post) {
        //If no matches, then go to next route
        //Something like this.next()?
      }
    },
   data: function() {
      return Posts.findOne(this.params.postId);
   }
  });
  this.route('profilePage', {
    // matches: '/harold'
    // matches: '/brendan'
    path: '/:username',
    data: function() {
      return Profiles.findOne(this.params.username);
    }
  });
});

你所描述的实际上只是一条路线:/:input, input可以是任何东西。正如@David Weldon所提到的,这不是一个好主意;它基本上颠覆了使用路由器的意义,并且每次URL更改时都会导致运行大量额外的代码和数据库查询。

也就是说,如果你真的想这样做,你只需要把所有的代码折叠成一个路由:

Router.map(function () {
  this.route('theOneRouteToRuleThemAll', {
    path: '/:input',
    data: function() {
      if (Profiles.findOne({username: this.params.input}) != null)
        return Profiles.findOne({username: this.params.input});
      else if (Posts.findOne({postId: this.params.input} != null)
        return Posts.findOne({postId: this.params.input};
      else
        return null; // No user or post found; could handle with notFoundTemplate
    }
  });
});