Frederik Witte
Frederik Witte

Reputation: 1345

Find all routes defined in Iron Router

Is there a way to add a site map dynamically for all paths which are defined in the Iron Router Router?

I'm thinking of something like this:

<ul>
    {{#each paths}}
        <li><a href="pathFor {{route}}">{{route}}</a></li>
    {{/each}}
</ul>

Also, maybe corresponding sub-paths which will be displayed in a child ul?

Obviously I could also just create the list manually, but for an app with 50+ links this is quite of a work.

Upvotes: 1

Views: 371

Answers (1)

KyleMit
KyleMit

Reputation: 30267

Certainly! As Kassym noted, Router.routes contains a list of all the routes. However it contains the router functions, so you'll have to go and grab their names with route.getName(). The default route doesn't have a name, so you'll have to grab the .path() instead.

The whole thing should look like this in your helper:

Template.allRoutes.helpers({
  paths: function () {
    var allRoutes = _.map(Router.routes, function(route){
      var routeName = typeof route.getName() === 'undefined' ?
                      route.path() :
                      route.getName(); 
      return {route: routeName}
    });
    return allRoutes
  }
});

And this in your template:

<template name="allRoutes">
  {{#each paths}}
    <li><a href="{{pathFor route}}">{{route}}</a></li>
  {{/each}}
</template>

Working Demo in MeteorPad

Note: Remember to enclose pathFor in curly brackets because it is a helper method. It will execute javascript and inherit the current datacontext, so you can pass it any property from the current context.

In order to display an sub paths of n depth, you can recursively call your template like this:

<template name="subpaths">
  <ul>
  {{#each subpaths}}
    <li>
      <a href="{{pathFor path}}">{{path}}</a>
      {{#if subpaths}} {{>subpaths}} {{/if}}
    </li>
  {{/each}}
  </ul>
</template>

Demo in meteor pad

For more info, see getting the names of all routes for the accounts-entry package

Upvotes: 2

Related Questions