2015-01-09 63 views
4

我想向當前由Iron Router呈現的導航列表項添加一個'active'類。使用Meteor和Iron路由器創建活動導航狀態

這裏是我的標記:

<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> 

我已經通過引導和各種文章閱讀,但無法找到該覆蓋的任何地方。假設我需要某種幫手?

回答

7

我想你可能會發現meteor-iron-router-active有用,因爲它有助手爲以下幾點:

  • isActiveRoute
  • isActivePath
+0

流星添加鐵 - 路由器活性 =>錯誤在解析參數: 在添加包鐵路由器活性: 錯誤:沒有這樣的包 – 2015-01-09 22:32:06

+0

看起來像鐵路由器活性與流星0.9.0不相容然後... – 2015-01-09 22:58:28

+1

我會建議升級流星,然後像這樣安裝它:** meteor add zimme:iron-router-active **。您可以在** atmospherejs.com上找到更多詳情:https://atmospherejs.com/zimme/iron-router-active**。 – 2015-01-10 02:02:16

4

這裏是我如何做到這一點。

首先,我運行這個(CoffeeScript的)當我設置了鐵路由器:

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

然後在我的導航每個地方我展示一個鏈接到一個新的頁面,我的HTML(玉在我的情況)看起來是這樣的:

a(href=path class=isActive) 

最後,助手(再次CoffeeScript中)爲有這樣一個鏈接任何模板,已經這樣:

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

注意,如果this.name不行,請嘗試:Router.current().route.getName()

-----可有可無的東西這條線之下-----

這不是必須的滿足您的要求,但我的數據 - 使用一個遞歸調用的模板來驅動我的導航,所以上面的代碼只在我的代碼中出現一次,但我從幾個不同的地方引用navElement模板。完全乾。這裏是我的兩個級深度的限制比如(再次玉):

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 

在哪裏這就是所謂的在我的側欄或頂欄的地方是這樣的:

each navElements 
     +navElement 

這個幫手:

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

我最初設置並根據用戶的不同進行更改,navRoots會話變量如下所示:

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) 

每個用戶都可以配置他/她自己的邊欄菜單。登出的用戶只有一個選項(登錄)。等完全數據控制。

+0

爲了得到這個工作,我需要在助手中使用'Router.current()。route.getName()'而不是'this.name'。 – 2015-03-25 01:46:15

+0

伊斯蘭會議組織。是的,我的助手可能還有其他東西能正確顯示this.name。接得好。謝謝。 – 2015-03-25 15:06:14