When using a regex in iron router, how to access the match?

后端 未结 3 1368
心在旅途
心在旅途 2020-12-20 09:57

Rather than having five different routes, I am trying to combined five different paths into a single function, but I still need to know which path it matched. So if I set up

3条回答
  •  醉话见心
    2020-12-20 10:24

    This is a typical scenario for Iron.Router custom route controller! Check the guide here If you need some code, let me know. ;)

    [Edit]

    1. First, you define a route controller for all your sites, which inherit from the RouteController.

      BaseController = RouteController.extend({
          // Put repeating logic for your sites here
      });
      
    2. After that, you define your routes seperatly, not via regex. This is much more modular and maintainable. The big point here is, you don't have to find out by complicated functions, which site is current.

      Router.map(function(){
          this.route('accounts', {
              path: '/accounts'
          });
      });
      
    3. Now, give your routes his own controller

      Router.map(function(){
          this.route('accounts', {
              path: '/accounts',
              controller: 'AccountsController'
          });
      });
      
    4. In this Example, your AccountsController needs to inherit from your new BaseController. Put all your route logic, which is specific for only this route, in your AccountsController

      AccountsController = BaseController.extend({
          // Put your specific route logic here
      });
      
    5. Make sure, your BaseController is loading by meteor before your routes. Check out Meteor File Load Order.You can do something like the following

      client/routes
      client/routes/routes.js
      client/routes/controller/AccountsController.js
      client/routes/controller/BaseController.js
      

提交回复
热议问题