Created
July 24, 2018 20:38
-
-
Save bsubedi26/eb41c3c359129dd965780592128f4eb9 to your computer and use it in GitHub Desktop.
jekyll categorize collections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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