Sorted navigation menu with Jekyll and Liquid

后端 未结 10 2153
清酒与你
清酒与你 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:45

    I've written a simple Jekyll plugin to solve this issue:

    1. Copy sorted_for.rb from https://gist.github.com/3765912 to _plugins subdirectory of your Jekyll project:

      module Jekyll
        class SortedForTag < Liquid::For
          def render(context)
            sorted_collection = context[@collection_name].dup
            sorted_collection.sort_by! { |i| i.to_liquid[@attributes['sort_by']] }
      
            sorted_collection_name = "#{@collection_name}_sorted".sub('.', '_')
            context[sorted_collection_name] = sorted_collection
            @collection_name = sorted_collection_name
      
            super
          end
      
          def end_tag
            'endsorted_for'
          end
        end
      end
      
      Liquid::Template.register_tag('sorted_for', Jekyll::SortedForTag)
      
    2. Use tag sorted_for instead of for with sort_by:property parameter to sort by given property. You can also add reversed just like the original for.
    3. Don't forget to use different end tag endsorted_for.

    In your case the usage look like this:

      {% sorted_for p in site.pages sort_by:weight %}
    • {{ p.title }}
    • {% endsorted_for %}

提交回复
热议问题