Sorted navigation menu with Jekyll and Liquid

后端 未结 10 2142
清酒与你
清酒与你 2020-12-07 11:57

I\'m constructing a static site (no blog) with Jekyll/Liquid. I want it to have an auto-generated navigation menu that lists all existing pages and highlight the current pag

10条回答
  •  感情败类
    2020-12-07 12:48

    I've solved this using a generator. The generator iterates over pages, getting the navigation data, sorting it and pushing it back to the site config. From there Liquid can retrieve the data and display it. It also takes care of hiding and showing items.

    Consider this page fragment:

    ---
    navigation:
      title: Page name
      weight: 100
      show: true
    ---
    content.
    

    The navigation is rendered with this Liquid fragment:

    {% for p in site.navigation %}
    
  • {{ p.navigation.title }}
  • {% endfor %}

    Put the following code in a file in your _plugins folder:

    module Jekyll
    
      class SiteNavigation < Jekyll::Generator
        safe true
        priority :lowest
    
        def generate(site)
    
            # First remove all invisible items (default: nil = show in nav)
            sorted = []
            site.pages.each do |page|
              sorted << page if page.data["navigation"]["show"] != false
            end
    
            # Then sort em according to weight
            sorted = sorted.sort{ |a,b| a.data["navigation"]["weight"] <=> b.data["navigation"]["weight"] } 
    
            # Debug info.
            puts "Sorted resulting navigation:  (use site.config['sorted_navigation']) "
            sorted.each do |p|
              puts p.inspect 
            end
    
            # Access this in Liquid using: site.navigation
            site.config["navigation"] = sorted
        end
      end
    end
    

    I've spent quite a while figuring this out since I'm quite new to Jekyll and Ruby, so it would be great if anyone can improve on this.

提交回复
热议问题