How to adjust Jekyll post order?

后端 未结 4 1715
长情又很酷
长情又很酷 2021-02-01 02:34

I have started a Jekyll based blog with a theme jekyll-now. I am new to Jekyll and how it operates (especially Liquid). I understand that new posts need to be as follows: 2014-1

4条回答
  •  失恋的感觉
    2021-02-01 02:39

    Jekyll just string-compares post paths when sorting, which is why the date format is year-month-day. Posts are internally also collections and you can see the sorting being invoked in reader.rb:

    # Sorts posts, pages, and static files.
    def sort_files!
      site.collections.each_value { |c| c.docs.sort! }
      site.pages.sort_by!(&:name)
      site.static_files.sort_by!(&:relative_path)
    end
    

    So it's using generic ruby methods to sort and implements the comparator in document.rb:

    # Compare this document against another document.
    # Comparison is a comparison between the 2 paths of the documents.
    #
    # Returns -1, 0, +1 or nil depending on whether this doc's path is less than,
    #   equal or greater than the other doc's path. See String#<=> for more details.
    def <=>(other)
      return nil unless other.respond_to?(:data)
    
      cmp = data["date"] <=> other.data["date"]
      cmp = path <=> other.path if cmp.nil? || cmp.zero?
      cmp
    end
    

    Which means it first compares the dates and only checks the text if needed.

    The date is special only if it somehow wasn't found (no metadata). For drafts it falls back to the file modification time, for the rest to the site time.

    So if you want to force a different ordering of posts from the same day, craft the start of the title in the filename to alphabetically sort first. Eg. 2020-01-01-a.md will come after 2020-01-01-b.md if you're listing posts in descending order.

提交回复
热议问题