流星的铁路由器-将多条路径路由到一个模板,但仍然是DRY [英] Meteor's Iron Router - Route multiple paths to one template but still DRY

查看:98
本文介绍了流星的铁路由器-将多条路径路由到一个模板,但仍然是DRY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将多个路径路由到同一模板。例如, / abc / home / home 都将显示 home 模板。路径也可以具有子路径,因此 abc / parent / child / parent / child 也应路由到同一路径。

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. 我可以简单地重复

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. 我还可以使用参数

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 /:,因为它会很乱。

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. 我也尝试使用 Router.go()

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

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


但这会删除 / abc / 的网址,对于我来说是不希望的。

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


  1. 我目前最好的解决方案是使用共享功能

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



如何有效地将多个路径路由到一个模板,而不重复自己?


推荐答案

使用正则表达式(regex)匹配 / home / abc / home

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

这篇关于流星的铁路由器-将多条路径路由到一个模板,但仍然是DRY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆