2016-03-02 21 views
2

我有一個簡單的問題,就是向當前的菜單項添加一個類。將課程添加到當前的導航項

我有以下頁面結構:

- index.jade 
- about.jade 
- articles/ 
    - _data.json 
    - index.jade 
    - blog-post-1.jade 
    - blog-post-2.jade 
- contact.jade 

現在,我創建了一個叫做類:.active,它僅適用於根頁面(指數接觸),但是當我點擊/articles活動類未被添加到文章li在菜單中。

我使用此代碼段從豎琴網站:

ul 
    li(class="#{ current.source == 'index' ? 'active' : '' }") 
    a(href="/") Home 
    li(class="#{ current.source == 'about' ? 'active' : '' }") 
    a(href="/about") About 
    li(class="#{ current.source == 'articles' ? 'active' : '' }") 
    a(href="/articles") Articles 
    li(class="#{ current.source == 'contact' ? 'active' : '' }") 
    a(href="/contact") Contact 

無論我怎麼努力,我似乎​​無法得到.active菜單類在/articles也沒有任何文章頁的工作:articles/blog-post-1articles/blog-post-2等等。

同樣在豎琴現場我看到,您可以添加:

{ 
    path: ["articles", "hello-world"], 
    source: "hello-world" 
} 

但我不知道在哪裏添加。我將它添加到articles/_data.json文件中,但沒有奏效。

回答

3

所以,你實際上不必當前源和當前路徑,這是Harp在你的模板中提供的東西之一。你可以只顯示在頁面隨時像這樣的:

pre: code= JSON.stringify(current, 0, 2) 

說你是第一個博客後的網頁上,你會得到這樣的:

{ 
    source: "blog-post-1" 
    path: [ 
    "articles", 
    "blog-post-1" 
    ] 
} 

因此,在這種情況下,你的資產淨值沒有被激活,因爲current.source實際上不是articles,而是blog-post-1blog-post-2。解決該問題的最快捷的方法是:

li(class="#{ current.path[0] === 'articles' ? 'active' : '' }") 
    a(href="/articles") Articles 

這仍然應該對文章的索引頁以及工作,在豎琴的current object將看起來像:

{ 
    source: "index" 
    path: [ 
    "articles", 
    "index" 
    ] 
} 
+0

謝謝你的快速回復肯尼斯但我仍然無法將.active類添加到/ articles中的帖子中!當我點擊/文章時,該課程是活躍的,但是當我點擊「博客-1」時,課程沒有通過?! – user5898548

+1

嘗試註銷數據,以便您可以看到該頁面上實際存在的元數據是否與您的期望匹配: ''' pre:code = JSON.stringify(current,0,2) ''' ' – kennethormandy

+0

最後我用:#{current.source =='blog-post-2'?'active':''} – user5898548