dayuloli
dayuloli

Reputation: 17021

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

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?

Upvotes: 2

Views: 2126

Answers (2)

Bart S
Bart S

Reputation: 1808

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

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

Upvotes: 0

Larry Maccherone
Larry Maccherone

Reputation: 9523

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

Upvotes: 2

Related Questions