Jekyll - automate tag sub page generation with simple Python script

14 Jun 2019 Script #jekyll #python #automation #drone

Yesterday I automated my page builds with Drone.io, today I wanted to generate “tags subpages” that will provide a subpage for every tag.

I created a simple python script to automate that process.

import frontmatter, os

os.chdir("/drone/src") #Drone.io, change it if you use something else to automate builds.
dir = os.getcwd()
tags = []

if os.path.exists(dir + "/tag"):
    print("[Tag] Removing tag directory");
    os.rmdir(dir + "/tag")
print("[Tag] Creating tag directory");
os.mkdir(dir + "/tag")
print("[Tag] Looping thru posts");
for filename in os.listdir(dir + "/_posts"):
    if filename.endswith(".md"):
        with open(dir + "/_posts/" + filename) as f:
            post = frontmatter.load(f)
            if "tags" in post.keys():
                ptags = post["tags"]
                for tag in ptags:
                    if not tag in tags:
                        tags.append(tag)

for tag in tags:
    tag = tag.replace(" ", "-")
    if not os.path.isfile(dir + "/tag/" + tag + ".md"):
        page = []
        page.append("---")
        page.append("layout: tag")
        page.append("tag: " + tag)
        page.append("title: 'Tag " + tag + "'")
        page.append("---")
        page = "\n".join(page)
        with open(dir + "/tag/" + tag + ".md", "w") as file:
            file.write(page)
            print("[Tag] Created " + tag);

You will also need a tag layout:

---
layout: default
---
<h1>Tag: #{{page.tag}}</h1>
{% for post in site.posts %}
    {% for tag in post.tags %}
        {% if tag == page.tag %}
            <li><span>{{ post.date | date_to_string }}</span> &raquo; <a href="{{ post.url }}">{{ post.title }}</a></li>
        {% endif %}
    {% endfor %}
{% endfor %}

If you are using mine drone.io pipeline you can add it before build pipeline:

  generate-jekyll-tags:
    image: python:3.7.3
    commands:
      - pip3 install python-frontmatter
      - python3 generateTags.py