Meteor's Iron Router - Route multiple paths to one template but still DRY

本秂侑毒 提交于 2019-12-07 18:41:25

问题


I want to route multiple paths to the same template. For example, /abc/home and /home will both show the home template. The paths can also have subpaths, so abc/parent/child and /parent/child should route to same path also.


  1. I can simply repeat:

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

But I don't want to repeat it. If I want to change the template to route to, I want to only change it once - for convenience and also to minimize errors.


  1. I can also use parameters:

    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;
        }
      }
    });
    

But this, again, is repeating myself. Also, there can subpaths, and I don't want to define routing for /:_abc/:parent/:children and /:_abc/:grandparent/:parent/:children/:, because it will be messy.


  1. I also tried using Router.go():

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

But this removes the /abc/ from the url, which is undesired in my case.


  1. The best solution I have right now is using a shared function:

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

Can I instead do something like specify an array, or comma-separated string:

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');
});

How do I efficiently route multiple paths to one template, while not repeating myself?


回答1:


Use a regular expression (regex) that matches both /home and /abc/home.




回答2:


I made a second template that only includes the first. In your case this might look like this:

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


来源:https://stackoverflow.com/questions/27976879/meteors-iron-router-route-multiple-paths-to-one-template-but-still-dry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!