Jekyll - Automatically highlight current tab in menu bar

后端 未结 12 1009
鱼传尺愫
鱼传尺愫 2020-12-22 15:34

I am using github to host a static site and Jekyll to generate it.

I have a menu bar (as

    ) and would like the
  • correspo
12条回答
  •  感动是毒
    2020-12-22 15:50

    Here's my solution which I think is the best way to highlight the current page:

    Define a navigation list on your _config.yml like this:

    navigation:
      - title: blog
        url: /blog/
      - title: about
        url: /about/
      - title: projects
        url: /projects/
    

    Then in your _includes/header.html file you must loop through the list to check if the current page (page.url) resembles any item of the navigation list, if so then you just set the active class and add it to the tag:

    
    

    And because you're using the contains operator instead of the equals = operator, you don't have to write extra code to make it work with URLs such as '/blog/post-name/' or 'projects/project-name/'. So it works really well.

    P.S: Don't forget to set the permalink variable on your pages.

提交回复
热议问题