【问题标题】:Meteor's Iron Router - Route multiple paths to one template but still DRYMeteor's Iron Router - 将多条路径路由到一个模板但仍然 DRY
【发布时间】:2015-03-14 15:21:31
【问题描述】:

我想将多个路径路由到同一个模板。例如,/abc/home/home 都将显示 home 模板。路径也可以有子路径,所以abc/parent/child/parent/child 也应该路由到相同的路径。


  1. 我可以重复一遍

    Router.route('/home', function () {
      this.render('home');
      Session.set('menu', 'home');
    });
    Router.route('/abc/home', function () {
      this.render('home');
      Session.set('menu', 'home');
    });
    

但我不想重复。如果我想更改要路由到的模板,我只想更改一次 - 方便并尽量减少错误。


  1. 我也可以使用参数

    Router.route('/:_abc/:path', function () {
      if(this.params._abc == 'abc') {
        switch(this.params.path) {
          case 'home':
            this.render('home');
            break;
          case 'someotherroute':
            this.render('someotherroute');
            break;
        }
      }
    });
    

但这又在重复我自己。另外,可以有子路径,我不想为/:_abc/:parent/:children/:_abc/:grandparent/:parent/:children/:定义路由,因为会很乱。


  1. 我也尝试过使用Router.go()

    Router.route('/:_abc/:route', function () {
      if(this.params._abc == 'abc') {
        Router.go('/' + this.params.route);
      }
    });
    

但这会从网址中删除/abc/,这在我的情况下是不受欢迎的。


  1. 我现在最好的解决方案是使用共享函数

    var renderHome = function () {
      this.render('home');
      Session.set('menu', 'home');
    }
    
    Router.route('/home', renderHome());
    Router.route('/abc/home', renderHome());
    

我可以改为指定一个数组或逗号分隔的字符串

Router.route(['/home', '/abc/home'], function () {
  this.render('home');
  Session.set('menu', 'home');
});

// or

Router.route('/home, /abc/home', function () {
  this.render('home');
  Session.set('menu', 'home');
});

如何有效地将多条路径路由到一个模板,而不是重复自己?

【问题讨论】:

  • 您是否尝试过创建一个同时匹配/home/abc/home 的正则表达式(regex)?
  • @LarryMaccherone 不,我还没有尝试过,看起来像是要走的路。现在我正在使用类似于stackoverflow.com/a/27456029/2317532 的东西,稍后会重构。感谢您的建议。
  • 好的,我将其添加为答案,以便您接受。当您找出确切的正则表达式时,请告诉我,我将更新我的答案以供将来参考。 :-)

标签: meteor routing dry iron-router


【解决方案1】:

使用同时匹配/home/abc/home 的正则表达式 (regex)。

【讨论】:

    【解决方案2】:

    我制作了第二个模板,其中仅包含第一个模板。在您的情况下,这可能如下所示:

    <template name="abcHome">
      {{> home}}
    </template>
    

    【讨论】:

      猜你喜欢
      • 2015-03-14
      • 2016-01-16
      • 2015-02-12
      • 1970-01-01
      • 2014-12-28
      • 2018-11-21
      • 2015-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多