如何为 Jekyll 中的每个帖子创建排序类别(作为插件;红宝石)



我有一个使用 Jekyll 的网站,我希望对我的类别进行排序。我成功地按以下方式对所有类别进行排序:

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

在插件 sorted_categories.rb 中。这创造了site.sorted_categories。现在我还希望每个帖子的类别排序。post.sorted_categories我想通过添加

  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

到上面的代码,但它不起作用。

(我知道我将如何直接在帖子中对类别进行排序,但我想知道它如何作为插件工作)

如何更正代码,使其正常工作?也许,我并不完全了解 Jekyll 的模具内部结构,所以我也对其他(优雅的)解决方案持开放态度。

通过使用此问题中提到的解决方法,可以执行以下操作:

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

最新更新