My Python Script for Making Blog Posts on Hugo

I haven’t written a lot of blog posts yet, but I thought it would be useful (and fun) to make a Python script that can help me create blog posts more easily.

This site is built using Hugo, so to make a post in either my blog or portfolio, I need to enter hugo new /[content folder name]/[filename] in the command line, which creates the Markdown file for the post.

For my Python script, what I wanted to do is to enter the title of my post, automatically slugify it (converting it to lower case and changing spaces to hyphens so the title can be used as a URL), then use the slugified title in my Markdown file’s filename. So if I enter “My Python Script for Making Blog Posts on Hugo” as the title, the script would automatically create a Markdown file named my-python-script-for-making-blog-posts-on-hugo.md.

This is the script:

import unicodedata
import re
import os
from datetime import datetime

# This helps you create Markdown files in the content folder of a Hugo site.

folder_name = "posts"  # change this to your target content folder
title = ""


def slugify(value, allow_unicode=False):
    # Taken from https://github.com/django/django/blob/master/django/utils/text.py
    value = str(value)
    if allow_unicode:
        value = unicodedata.normalize("NFKC", value)
    else:
        value = (
            unicodedata.normalize("NFKD", value)
            .encode("ascii", "ignore")
            .decode("ascii")
        )
    value = re.sub(r"[^\w\s-]", "", value.lower())
    return re.sub(r"[-\s]+", "-", value).strip("-_")


filename = slugify(title) + ".md"

current_date = datetime.now().strftime("%Y-%m-%dT%H:%M:%S+08:00")

md_content = f"""---
title: "{title}"
date: {current_date}
description: ""
image: ""
tags: []
draft: false
---
"""

final_path = "content/" + folder_name

# Ensure the target folder exists
if not os.path.exists(final_path):
    os.makedirs(final_path)

# Create the Markdown file in the specified folder
with open(os.path.join(final_path, filename), "w") as file:
    file.write(md_content)

For folder_name: my blog posts are in the /content/posts folder of my Hugo site, so my folder_name is set to "posts".

I did consider other methods. There is a VS Code extension called Hugo Helper that has a command that to create content based on archetypes. But it doesn’t make the filename lowercase, so my website’s URLs wouldn’t be in lowercase either—making the URL look messy.

I also considered using archetypes, but its title case function would affect words that aren’t capitalised in a traditional way (like iOS), so I would need to edit the title later.