Search code examples
meteortwitter-bootstrap-3iron-routerflow-router

Highlight active route in bootstrap nav when using Flow-Router


So I found this Navigation Bar feature with Bootstrap-3, but as of now I am using Flow-Router instead of Iron-Router. Thus I am seeking to transform this helper function into Flow-Router terms:

Template.navItems.helpers({
    activeIfTemplateIs: function (template) {
      var currentRoute = Router.current();
      return currentRoute &&
        template === currentRoute.lookupTemplate() ? 'active' : '';
    }
});

I have made my own attempt at fixing the problem (haven't bothered testing it though, as many parts of my site/app are still not functional), but I require confirmation in the form of a "yes" or "no" and perhaps a bit more information on what I did wrong.

Template.navItems.helpers({
    activeIfTemplateIs: function (template) {
      var currentRoute = FlowRouter.current();
      return currentRoute &&
        template === currentRoute.name ? 'active' : '';
    }
});

I guided myself from the Flow-Router API. Is this solution correct or is it for one reason or another strictly bound to be used with Iron-Router?


Solution

  • After thinking about your real issue a bit further, I realized I'm doing this is in my app in a completely different way and that perhaps you might find that pattern useful. My app also uses bootstrap and has a nav where I want to highlight the active route (and un-highlight all other routes).

    In iron-router, I do:

    onAfterAction(){
      const selector = '.nav a[href="/' + Router.current().route.getName() + '"]'; // the nav item for the active route (if any)
      $('.nav-active').removeClass('nav-active'); // unhighlight any previously highlighted nav
      $(selector).addClass('nav-active'); // highlight the current nav (if it exists, many routes don't have a nav)
    }
    

    In Flow-Router, onAfterAction is replaced by triggersExit so you can do:

    triggersExit(){
      const selector = '.nav a[href="' + FlowRouter.current().path + '"]';
      $('.nav-active').removeClass('nav-active');
      $(selector).addClass('nav-active');
    }
    

    I found this much more convenient than mucking with the spacebars templates.

    FYI, you have a couple options to get the route name:

    FlowRouter.getRouteName() // reactive
    

    or

    FlowRouter.current().route.name // NOT reactive