问题
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.
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.
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.
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.
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