Search code examples
meteoriron-router

How to get route name by URL in Meteor using Iron Router


I know that to get current route's name I would need use do Router.current().route.getName(). What if I need to get route's name by given URL (not current URL).

Let's say I have list of URLS

urls = ['/orders', '/clients', '/clients/tJa84ogQ3cvpxMJ7G']

And I have following Iron Router configuration :

Router.route('/orders', {name: 'ordersList'});

Router.route('/clients', {name: 'clientsList'});

Router.route('/clients/:_id', {
  name: 'clientPage',
  data: function() {
    return Clients.findOne(this.params._id);
  }
});

How from urls list I could get list of route names?


Solution

  • So, from a list of URL, get the list of all matching routes?

    var urls = ['/path1', '/path2/subpath', ...];
    var matchingRoutes = _.filter(Router.routes, function(route) {
      return _.contain(urls, route.path);
    });
    

    If you want the route names specifically:

    var matchingRoutesNames = _.pluck(matchingRoutes, 'name');
    

    More about underscore

    However, this will not work for a URL with set parameters like '/clients/tJa84ogQ3cvpxMJ7G' in your example, since the corresponding path is not the same. Here, it would be /clients/:clientId.
    You could maybe make it work with some Regex black magic and careful splitting of the URL, but it would get complicated.