Skip to content

Instantly share code, notes, and snippets.

@muziejus
Last active May 1, 2018 23:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save muziejus/904edb7cf8e9abe8a3a1069c9773f11d to your computer and use it in GitHub Desktop.
Save muziejus/904edb7cf8e9abe8a3a1069c9773f11d to your computer and use it in GitHub Desktop.
Jekyll Rakefile to generate tag pages without plugins for use in gh-pages sites.
# This is a ruby port of Long Qian's:
#
# https://github.com/qian256/qian256.github.io/blob/master/tag_generator.py
#
# which is a python script that accompanies this useful webpage on creating
# tags for Jekyll without plugins:
#
# http://longqian.me/2017/02/09/github-jekyll-tag/
#
# This Rakefile uses Jekyll's internals to generate the list, as opposed to
# crawling through "_posts/", like the python original. Hence, it works for all
# collections. ("posts" are a default collection)
#
# Simply put, it scans all of the site's *collections* (so posts and anything
# else that's defined as a collection in _config.yml) for the "tags" key and
# builds an array out of them. Then, it autogenerates a page for each tag.
# It assumes you've followed Long Qian's instructions for structuring tags, etc.
#
# Unfortunately, every time a new tag is added, this rake task needs to be run
# again.
#
# To install:
# 1. Put this file in the root directory of your Jekyll install (the same
# folder as _config.yml)
# 2. Add "gem 'rake'" to your Gemfile
# 3. Install rake with "bundle install"
#
# To use:
# 1. "bundle exec rake build_tags"
require "jekyll"
task :build_tags do
puts "Building up the tag files…"
tags_dir = "tags" # set the tags folder
if File.directory?(tags_dir) # create the tags folder if it doesn't exist
puts "Tags directory (./#{tags_dir}) exists."
else
puts "Tags directory (./#{tags_dir}) does not exist. Creating it…"
Dir.mkdir(tags_dir)
end
site = Jekyll::Site.new(Jekyll.configuration) # init Jekyll site
reader = Jekyll::CollectionReader.new(site) # init Jekyll collections reader
tags = reader.read.keys.map do |collection| # iterate over the collections
reader.read[collection].docs.map do |document| # and over every coll's docs
document.data["tags"] # add its tags array to the array
end
end
tags.flatten!.uniq!.each do |tag| # flatten array of arrays, use only uniques, and iterate
File.open("./#{tags_dir}/#{tag}.md", "w") do |f| # create a blank file for the tag
f.puts "---"
f.puts "title: \"Tag: #{tag}\""
f.puts "layout: tagpage"
f.puts "tag: #{tag}"
f.puts "robots: noindex"
# add any other metadata you want to include—permalink, etc.—here.
f.puts "---"
end
end
puts "#{tags.count} tags generated!"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment