Skip to content

Instantly share code, notes, and snippets.

@bsubedi26
Created July 24, 2018 20:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bsubedi26/eb41c3c359129dd965780592128f4eb9 to your computer and use it in GitHub Desktop.
Save bsubedi26/eb41c3c359129dd965780592128f4eb9 to your computer and use it in GitHub Desktop.
jekyll categorize collections
# frozen_string_literal: true
require "jekyll"
module Jekyll
class CategorizePageGenerator < Jekyll::Generator
safe true
def get_collection(name)
@site.collections[name] ? @site.collections[name].docs : []
end
def add_to_frontmatter(page, values)
values.each do |key, value|
# add to the page front matter header
page.data[key] = value
end
end
def isValid?(item)
path = item.relative_path.split('/')
# if category folder has no sub categories
if path.length == 3
header_values = { "category" => path[1] }
add_to_frontmatter(item, header_values)
return false
end
return true
end
def get_header_values_to_add(item)
path = item.relative_path.split('/')
# ignore index.md and index.html files
if path[1] and path[1] != "index.html" and path[1] != "index.md"
category = path[1]
end
if path[2] and path[2] != "index.html" and path[2] != "index.md"
sub_category = path[2]
end
return {
"category" => category,
"sub_category" => sub_category
}
end
# main generator init function
def generate(site)
@site = site
# The collections to add category/sub category front matter values
# IMPORTANT: specify collection in _data/categorize_collection.yml
# or defaults to pages collection
collections = @site.data["categorize_collections"] || ["pages"]
for c in collections
for item in get_collection(c)
valid_category = isValid?(item)
if valid_category
header_values = get_header_values_to_add(item)
add_to_frontmatter(item, header_values)
end
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment