user5898548
user5898548

Reputation: 73

Add class to current nav item

I have simple question about adding a class to the current menu item.

I have the following page structure:

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

Now I created a class called: .active and it only works on the root pages (index, about and contact) but when I click on /articles the active class is not being added to the articles li in the menu.

I am using this code snippet from the Harp site:

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

No matter what I try I can't seem to get the .active menu class to work on /articles nor any of the article pages: articles/blog-post-1 or articles/blog-post-2 and so on.

Also on the Harp site I saw you can add:

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

But I am not sure where to add it. I added it to the articles/_data.json file but didn't work.

Upvotes: 2

Views: 257

Answers (1)

kennethormandy
kennethormandy

Reputation: 2150

So you don’t actually have to add the current source and the current path, that’s one of the things Harp makes available in your templates. You can just show it on the page anytime like this:

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

Say you are on the first blog post page, you’ll get something like:

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

So in this case, your nav isn’t being activated because the current.source isn’t actually articles, it’s blog-post-1 or blog-post-2. The quickest way to fix the problem would be:

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

This should still work for the articles index page as well, where Harp’s current object will look like:

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

Upvotes: 3

Related Questions