Meteor 的 Iron Router - 将多个路径路由到一个模板,但仍然是 DRY

标签 meteor routes dry iron-router

我想将多个路径路由到同一模板。例如,/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');
    });
    

但我不想重复。如果我想更改要路由到的模板,我只想更改一次 - 为了方便并最大限度地减少错误。


  • 我还可以使用参数:

    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/定义路由: ,因为它会很困惑。


  • 我还尝试使用Router.go():

    Router.route('/:_abc/:route', function () {
      if(this.params._abc == 'abc') {
        Router.go('/' + this.params.route);
      }
    });
    
  • 但这会从网址中删除 /abc/,这在我的情况下是不需要的。


  • 我现在拥有的最佳解决方案是使用共享函数:

    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)。

    关于Meteor 的 Iron Router - 将多个路径路由到一个模板,但仍然是 DRY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27976879/

    相关文章:

    javascript - MeteorJs模板条件显示不同的模板

    javascript - meteor 从事件更新模板

    c# - 具有路由和查询字符串参数的 ASP.NET http配置映射

    javascript - 如何使用get发送数据而不在url中显示参数?

    java - 如何避免java中半重复的方法组?

    c++ - 缩小 C++ 模板代码上的样板代码

    javascript - Meteor 环境变量在生产中无效

    javascript - 是否可以在 Meteor 空格键模板中切换集合焦点?

    java - Apache Camel Junit 保持 Context 运行

    jQuery 结合多个函数以实现更简洁的编码