我想将多个路径路由到同一模板。例如,/abc/home
和 /home
都将显示 home
模板。路径也可以有子路径,因此 abc/parent/child
和 /parent/child
也应该路由到同一路径。
我可以简单地重复:
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/