Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Generate a blog-style index page written in markdown
"""Generate a blog-style index page written in markdown.
A header line with link to page, followed by a few lines of the story.
import os
from pathlib import Path
import dateutil.parser
from inspect import getsourcefile
here = os.path.dirname(os.path.abspath(getsourcefile(lambda:0)))
src = os.path.join(here, "blog")
page = ""
docs = Path(src).rglob("*.md")
def parse_endmatter(lines):
"""Look for yaml style metadata at end of file and attempt to parse it.
Only 'date' for now and ignoring any others.
# date to use if no date is found
parsed_date = dateutil.parser.parse("1970")
for line in reversed(lines):
if line.startswith("---"):
# remove formatting with '*' or '_' from outer ends, also whitespace
line = line.strip().lstrip('*_').rstrip('*_')
if line.lower().startswith('date:'):
mydate = line.split('date:')[1]
# print(mydate)
parsed_date = dateutil.parser.parse(mydate)
return parsed_date
posts = {}
for f in docs:
if not"index"):
doc = Path(f.resolve())
link_path = Path(f.resolve()).relative_to(src).as_posix()
text = []
with open(f.resolve(), encoding="utf8") as ff:
lines = ff.readlines()
doc_date = parse_endmatter(lines)
# convert header level 1 to level 2 and link to the page
title = lines[0].rstrip().lstrip("# ")
text.append(f"## [{title}]({link_path}) <sup>{}</sup>\n\n")
# write blog intro
text.append(f" [(...)]({link_path})\n\n")
# text.append(f"_{}_\n\n")
posts[link_path] = [doc_date, text]
with open(os.path.join(src,page), 'w') as out_file:
out_file.write("# Blog\n\n")
# Posts is dict of (relative file path): (date), (intro blurb text)
sorted_posts = sorted(posts.items(), key=lambda item:item[1], reverse=True)
for p in sorted_posts:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment