Daniel Krenn
Daniel Krenn

Reputation: 251

How to created sorted categories for each post in Jekyll (as Plugin; Ruby)

I have a website using Jekyll and I want my categories to be sorted. I succeeded sorting all the categories by:

module Jekyll
  class SortedCategoriesBuilder < Generator
    safe true
    priority :high

    def generate(site)
      site.config['sorted_categories'] = site.categories.sort { |a,b| a[0] <=> b[0] }
    end   
  end
end

in a plugin sorted_categories.rb. This created site.sorted_categories. Now I also want sorted categories for each posting. I want to add a post.sorted_categories for each post in site.posts by adding

  for post in site.posts
    post.class.module_eval { attr_accessor :sorted_categories } 
    post.sorted_categories = post.categories.sort { |a,b| a[0] <=> b[0] }
  end

to the code above, but it doesn't work.

(I know how I would sort the categories directly in the posting, but I'd like to know how it works as plugin)

How do I correct the code, so that it works? Perhaps, I do not understand die internal structure of Jekyll completely, so I'm also open for other (elegant) solutions.

Upvotes: 1

Views: 237

Answers (1)

Daniel Krenn
Daniel Krenn

Reputation: 251

By using a workaround mentioned in this question the following works:

module Jekyll
  class Post
    def sorted_categories
      self.categories.sort { |a,b| a[0] <=> b[0] }
    end

    def to_liquid(attrs = ATTRIBUTES_FOR_LIQUID)
      super(attrs + %w[
      sorted_categories
    ])
    end
  end
end

Upvotes: 1

Related Questions