Skip to content

Instantly share code, notes, and snippets.

@rfong
Created May 17, 2021 22:51
Show Gist options
  • Save rfong/9e7a9e99a1295deaa58f81548eaf66d6 to your computer and use it in GitHub Desktop.
Save rfong/9e7a9e99a1295deaa58f81548eaf66d6 to your computer and use it in GitHub Desktop.
Automatic tag-page generator for all post tags on a Jekyll site. See https://rfong.github.io/rflog/2020/02/28/jekyll-tags/
# Filename: __plugins/compile_tags.py
'''
This script generates tag pages for all your post tags for a
Jekyll site. It is invoked from a plugin after post_write.
Run it from the project root if testing.
Convention expected here for tag names is r/[-\w\d]+/
'''
import glob
import os
POST_DIR = '_posts/'
TAG_DIR = 'tag/'
# Collect all tags from all posts.
all_tags = []
for fname in glob.glob(POST_DIR + '*.md'):
with open(fname, 'r') as f:
for line in f:
line = line.strip().replace('[', '').replace(']', '')
# Find tags & cut them.
if line.startswith('tags: '):
all_tags += [
t.strip() for t in line[len("tags: "):].split(',')]
break
all_tags = sorted(list(set(all_tags)))
# Remove old tag pages
old_tags = glob.glob(TAG_DIR + '*.md')
for tag in old_tags:
os.remove(tag)
# Create tag directory if it does not exist
if not os.path.exists(TAG_DIR):
os.makedirs(TAG_DIR)
# Write new tag pages.
TAG_PAGE_TEMPLATE = '''---
layout: tagpage
tag: {tag}
robots: noindex
---'''
for tag in all_tags:
with open(TAG_DIR + tag + '.md', 'a') as f:
f.write(TAG_PAGE_TEMPLATE.format(tag=tag))
# Filename: __plugins/compile_tags.rb
# Jekyll post_write hook to run the page generator script
Jekyll::Hooks.register :posts, :post_write do
system("python _plugins/compile_tags.py")
end
@harriott
Copy link

harriott commented Jun 4, 2023

Very helpful, thanks. Implemented on my GitHub Pages Jekyll site using minima theme.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment