Jekyll - Automatically highlight current tab in menu bar

后端 未结 12 938
鱼传尺愫
鱼传尺愫 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:53

    Yes you can do this.
    To accomplish this we will take advantage of the fact that the current page is always represented by the liquid variable: page in the template, and also that each post/page has a unique identifier in its page.url attribute.

    This means that we just have to use a loop to build our navigation page, and by doing so we can check page.url against every member of the loop. If it finds a match, it knows to highlight that element. Here we go:

      {% for node in site.pages %}
        {% if page.url == node.url %}
          
  • {{node.title}}
  • {% else %}
  • {{node.title}}
  • {% endif %} {% endfor %}

    This works as expected. However you probably don't want all your page's in your nav bar. In order to emulate page "grouping" you can something like this:

    ## Put the following code in a file in the _includes folder at: ./_includes/pages_list
    
    {% for node in pages_list %}
      {% if group == null or group == node.group %}
        {% if page.url == node.url %}
          
  • {{node.title}}
  • {% else %}
  • {{node.title}}
  • {% endif %} {% endif %} {% endfor %} {% assign pages_list = nil %} {% assign group = nil %}

    Now pages can be "grouped". To give a page a group you need to specify it in the pages YAML Front Matter:

    ---
    title: blah
    categories: blah
    group: "navigation"
    ---    
    

    Finally you can use your new code! Wherever you need your navigation to go in your template, simply "call" your include file and pass it some pages and the group you want to display:

      {% assign pages_list = site.pages %} {% assign group = 'navigation' %} {% include pages_list %}

    Examples

    This functionality is part of the Jekyll-Bootstrap framework. You can see exact documentation for the code outlined here: http://jekyllbootstrap.com/api/bootstrap-api.html#jbpages_list

    Finally you can see it in action within the website itself. Just look at the righthand navigation and you will see the current page is highlighted in green: Example highlighted nav link

提交回复
热议问题