Search code examples
meteoriron-router

How to avoid similar route in iron-router?


Sorry for the bad English.

I have a tabs with four tab, each has a route

<ul class="nav nav-tabs">
 <li role="presentation"><a href="{{pathFor 'menu.tab1'">tab1</a></li>
 <li role="presentation"><a href="{{pathFor 'menu.tab2'">tab2</a></li>
 <li role="presentation"><a href="{{pathFor 'menu.tab3'">tab3</a></li>
 <li role="presentation"><a href="{{pathFor 'menu.tab4'">tab4</a></li>
</ul>

And route.js

this.route('/menu/tab1', {
  name: 'menu.tab1',
  template: 'MenuTab1',
});         
this.route('/menu/tab2', {
  name: 'menu.tab2',
  template: 'MenuTab2',
});
this.route('/menu/tab3', {
  name: 'menu.tab3',
  template: 'MenuTab3',
});
this.route('/menu/tab4', {
  name: 'menu.tab4',
  template: 'MenuTab4',
});

Can I simplify these similar code?


Solution

  • As hinted by @Petr, you can refactor your code to use arrays.

    var tabs = [{
      label: "tab1",
      route: {
        path: "/menu/tab1",
        name: "menu.tab1",
        template: "MenuTab1"
      }
    },{
      [...]
    }];
    
    tabs.forEach(function(tab){
      var route = tab.route;
      Router.route(route.path,{
        name: route.name,
        template: route.template
      });
    });
    
    Template.tabs.helpers({
      tabs: tabs
    });
    

    HTML

    <template name="tabs">
      <ul class="nav nav-tabs">
        {{#each tabs}}
          <li role="presentation">
            <a href="{{pathFor route.name}}">label</a>
          </li>
        {{/each}}
      </ul>
    </template>
    

    If your tabs follow an exact pattern regarding naming scheme, you could even fo further :

    var tabs = [{
      id: "tab1",
      label: "Tab 1"
    },{
      [...]
    }];
    
    tabs = tabs.map(function(tab){
      function capitalizeFirstLetter(string) {
        return string.charAt(0).toUpperCase() + string.slice(1);
      }
      //
      return {
        label: tab.label,
        route: {
          path: "/menu/" + tab.id,
          name: "menu." + tab.id,
          template: "Menu" + capitalizeFirstLetter(tab.id)
        }
      };
    });