Skip to content

Instantly share code, notes, and snippets.

Created July 6, 2022 07:12
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Pelican plugin that adjusts markdown YAML front matter.
# Pelican plugin that adjusts markdown
# YAML front matter created by Netlify CMS et al.
# to be handled correctly as metadata in pelican.
# This plugin requires PyYAML .
import io
import datetime
import yaml
from pelican import signals
from markdown import Markdown
from pelican.readers import MarkdownReader
from pelican.utils import pelican_open
def fixup_yaml(str_in):
lines = str_in.split("\n")
yaml_block = []
line = lines.pop(0)
if line == "---":
while lines:
line = lines.pop(0)
if line == "---":
lines.insert(0, line)
if yaml_block:
meta_data = io.StringIO()
print("---", file=meta_data)
for k, v in yaml.safe_load(io.StringIO("\n".join(yaml_block))).items():
if isinstance(v, datetime.datetime):
v = v.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
print(f"{k}: {v}", file=meta_data)
print("---", file=meta_data)
meta_data = meta_data.getvalue()
meta_data = ""
return meta_data + "\n".join(lines)
class FixupMetaYamlReader(MarkdownReader):
def read(self, source_path):
self._source_path = source_path
self._md = Markdown(**self.settings['MARKDOWN'])
with pelican_open(source_path) as text:
text = fixup_yaml(text)
content = self._md.convert(text)
if hasattr(self._md, 'Meta'):
metadata = self._parse_metadata(self._md.Meta)
metadata = {}
return content, metadata
def add_reader(readers):
for k in MarkdownReader.file_extensions:
readers.reader_classes[k] = FixupMetaYamlReader
def register():
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment