In building a site powered by Jekyll and hosted by GitHub, I wanted the ability to highlight the current page's tab in the bar. I also wanted the bar to support second-level items (i.e. a dropdown), which proved somewhat tricky. This is the solution I arrived at after a few hours of fiddling around.
The contents of the navigation bar are contained in a data file located at _data/navigation.yml
. This makes it accessible via the site-wide Liquid element {{ site.data.navigation}}
. You can see the file for the formatting I used.
This data is used in the navigation file, located at _includes/navigation.html
(which is therefore able to be included in your templates via {% include navigation.html}
).
The first section of the file has a loop that accomplishes two things:
- Does the current element of the loop have the exact same URL as the current page?
- If not, does the current element of the loop fit inside the current page's URL? (This is for nested pages.)
In the event of (1), the loop sets the current_page
value and breaks. In the event of (2), the loop sets the current_page
value but continues to loop. This effectively means the loop is searching for a best-fit value for the current page's URL.
Then the navigation bar is built. It loops over each entry and immediately checks if the current element is the same as the current_page
value we found previously. If they are a match, a current
variable is created that contains the class identifier to highlight the tab. If they are not a match the current
variable must be set to null
. This is to ensure you don't accidentally end up with a cascading highlighting effect. (Trust me, it's unwanted.)
- Any page that does not have an entry in the
navigation.yml
file will highlight a page withurl: /
. - My method is only built for a single sub-level. You'd have to adjust it for further sub-levels.
I'm using this in my GitHub pages site, and it generates the list of links just fine. However, it doesn't highlight the selected page. I tried adding classes to the css file named "current" and it still doesn't work. Do you know why it might not be using the right css for the current link?