问题
I want to add a class of 'active' to the nav list item that is currently being rendered by Iron Router.
Here's my markup:
<ul>
<li>
{{#linkTo route="option1"}}
<span class="fa fa-fw fa-option"></span>
Option 1
{{/linkTo}}
</li><li>
{{#linkTo route="option2"}}
<span class="fa fa-fw fa-option"></span>
Option 2
{{/linkTo}}
</li>
</ul>
I've read through the guide and various articles but can't find this covered anywhere. Assuming I'll need some sort of helper?
回答1:
I think you might find meteor-iron-router-active useful, as it has helpers for the following:
- isActiveRoute
- isActivePath
回答2:
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.
来源:https://stackoverflow.com/questions/27868594/creating-active-navigation-state-with-meteor-and-iron-router