Creating active navigation state with Meteor and Iron Router

*爱你&永不变心* 提交于 2019-12-05 16:58:10

I think you might find meteor-iron-router-active useful, as it has helpers for the following:

  • isActiveRoute
  • isActivePath

Here's how I do it.

First, I run this (CoffeeScript) when I set up iron router:

Router.onAfterAction(() ->
  Session.set('active', @route.getName())
)

Then for each place in my nav where I show a link to a new page, my html (jade in my case) looks like this:

a(href=path class=isActive)

Last, the helper (again CoffeeScript) for any template that has such a link, has this:

Template.navElement.helpers(
  isActive: () ->
    if this.name is Session.get('active')
      return "active"
    else
      return ""
)

Note, if this.name doesn't work, try: Router.current().route.getName()

----- Optional extra stuff below this line -----

This is not required to satisfy your request, but I data-drive my navigation with a single recursively-called template so the code above only occurs once in my code, but I reference the navElement template from several different places. Totally DRY. Here is my two-level deep restricted example (again Jade):

template(name="navElement")
  li
    a(href=path class=isActive)
      if icon
        i.fa.fa-fw(class=icon)
      | #{label}
      if children
        span.fa.arrow
    if children
      ul.nav.nav-second-level
        each children
          +navElement

And the place in my sidebar or topbar where this is called looks like this:

    each navElements
      +navElement

with this helper:

Template.sidebar.helpers(
  navElements: () ->
    return Session.get('navRoots')
)

I set initially and change from time to time depending upon what the user does, the navRoots session variable with something like this:

    navRoots = [
      {icon:"fa-gear", label:"Menu item 1", children: [
        {label: "Sub menu item 1.a"},
        {label: "Sub menu item 1.b"}
      },
      {label: "Menu item 2"}
    ]
    Session.set('navRoots', navRoots)

Each user can configure his/her own sidebar menu. Logged out users have only one option (Sign In). Etc. Totally data controlled.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!