Skip to content

Instantly share code, notes, and snippets.

@emordonez
Created May 13, 2021 20:10
Show Gist options
  • Save emordonez/ecb5d88c0be3eeeec48380c36739dba3 to your computer and use it in GitHub Desktop.
Save emordonez/ecb5d88c0be3eeeec48380c36739dba3 to your computer and use it in GitHub Desktop.
Use this script with a Nuxt Content site to emulate Hugo's use of archetypes to create new content. Easily extendable with different templates for different types of content.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from datetime import date
from string import punctuation
from sys import argv
import pathlib
import yaml
# Replace with absolute paths to your Nuxt Content directory and frontmatter template
# Python doesn't recognize the "~/" alias
CONTENT_DIR = "/home/user/absolute/path/to/content"
TEMPLATE = "/home/user/absolute/path/to/template.yaml"
# Provide a default title if no title is given
if len(argv) == 1:
the_title = "New blog post"
# Takes only the first token, so enclose the desired title in double quotes:
# e.g. newpost "This is my title"
else:
the_title = argv[1]
today = date.today()
the_date = today.strftime("%Y-%m-%d")
year = today.strftime("%Y")
month = today.strftime("%m")
# Template at a minimum must have title and date properties
with open(TEMPLATE) as template:
frontmatter = yaml.load(template, Loader=yaml.FullLoader)
frontmatter["title"] = the_title
frontmatter["date"] = the_date
# Format the path to your post however you organize your content
# e.g. /content/blog/2021/05
post_dir = CONTENT_DIR + "/{year}/{month}".format(year=year, month=month)
pathlib.Path(post_dir).mkdir(parents=True, exist_ok=True)
# Slugify the title
file_name = the_title.strip(punctuation).lower().replace(' ', '-') + ".md"
with open(post_dir + "/" + file_name, "w") as new_post:
new_post.write("---\n")
for k, v in frontmatter.items():
# Coerce None to an empty string, otherwise will write the string "None"
if v is None:
v = ''
new_post.write("{key}: {value}\n".format(key=k, value=v))
new_post.write("---\n")
# To run this script anywhere, you can remove the .py extension and make it
# executable with `chmod +x newpost`. Move it somwhere in your PATH, like
# /usr/local/bin. Now you can run `newpost "New blog post!"` from any
# terminal session.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment