Pelican plugin that adjusts markdown YAML front matter.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Pelican https://pypi.org/project/pelican/ plugin that adjusts markdown | |
# YAML front matter created by Netlify CMS https://www.netlifycms.org/ et al. | |
# to be handled correctly as metadata in pelican. | |
# This plugin requires PyYAML https://pypi.org/project/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 == "---": | |
break | |
yaml_block.append(line) | |
else: | |
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() | |
else: | |
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) | |
else: | |
metadata = {} | |
return content, metadata | |
def add_reader(readers): | |
for k in MarkdownReader.file_extensions: | |
readers.reader_classes[k] = FixupMetaYamlReader | |
def register(): | |
signals.readers_init.connect(add_reader) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment