2

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.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129

1 Answers1

3

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"
  ]
}
kennethormandy
  • 2,080
  • 14
  • 16
  • Thank you for the quick reply Kenneth but I still can't get the class of .active to be added to the posts in /articles?! When I click on /articles the class is active but when I click on "blog-post-1" the class does not get passes?! – user5898548 Mar 03 '16 at 09:20
  • 1
    Try logging out the data so you can see what metadata is actually present on that page to see if it is matching your expectations: ``` pre: code= JSON.stringify(current, 0, 2) ``` – kennethormandy Mar 03 '16 at 22:43
  • At the end I used: #{ current.source=='blog-post-2'?'active':'' } – user5898548 Mar 08 '16 at 11:17