From d028d15585a37629a373316d7e29c23fe23f18ad Mon Sep 17 00:00:00 2001 From: Frederik Ring Date: Fri, 6 Dec 2019 16:55:54 +0100 Subject: [PATCH] add markdown decorator plugin --- homepage/pelicanconf.py | 6 +++- homepage/plugins/decorate_content/__init__.py | 1 + .../decorate_content/decorate_content.py | 33 +++++++++++++++++++ homepage/requirements.txt | 1 + 4 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 homepage/plugins/decorate_content/__init__.py create mode 100644 homepage/plugins/decorate_content/decorate_content.py diff --git a/homepage/pelicanconf.py b/homepage/pelicanconf.py index 5fd4540..6fa44b5 100644 --- a/homepage/pelicanconf.py +++ b/homepage/pelicanconf.py @@ -39,8 +39,12 @@ DIRECT_TEMPLATES = ['sitemap'] SITEMAP_SAVE_AS = 'sitemap.xml' PLUGIN_PATHS = ['./plugins'] -PLUGINS = ['assets'] +PLUGINS = ['decorate_content', 'assets'] +DECORATE_CONTENT = { + # maps any CSS selector to a list of classes to be added + # 'p': ['pv0', 'dim'] +} GITHUB_ORG = 'https://github.com/offen' CONTACT_EMAIL = 'hioffen@posteo.de' diff --git a/homepage/plugins/decorate_content/__init__.py b/homepage/plugins/decorate_content/__init__.py new file mode 100644 index 0000000..1dd5d68 --- /dev/null +++ b/homepage/plugins/decorate_content/__init__.py @@ -0,0 +1 @@ +from .decorate_content import * diff --git a/homepage/plugins/decorate_content/decorate_content.py b/homepage/plugins/decorate_content/decorate_content.py new file mode 100644 index 0000000..21c0f4e --- /dev/null +++ b/homepage/plugins/decorate_content/decorate_content.py @@ -0,0 +1,33 @@ +from json import loads + +from pelican import signals +from pelican.contents import Article, Page, Static +from bs4 import BeautifulSoup + + +def content_object_init(instance): + if isinstance(instance, (Article, Page, Static)): + plugin_settings = instance.settings.get("DECORATE_CONTENT", {}) + content_overrides = ( + instance.metadata.get("decorate_content", None) + if instance.metadata is not None + else None + ) + + settings = plugin_settings.copy() + settings.update( + loads(content_overrides) if content_overrides is not None else {} + ) + + soup = BeautifulSoup(instance._content, "html.parser") + + for selector, class_names in settings.items(): + elems = soup.find_all(selector) + for elem in elems: + elem["class"] = elem.get("class", []) + class_names + + instance._content = soup.decode() + + +def register(): + signals.content_object_init.connect(content_object_init) diff --git a/homepage/requirements.txt b/homepage/requirements.txt index 401a5fb..5a8b71c 100644 --- a/homepage/requirements.txt +++ b/homepage/requirements.txt @@ -3,3 +3,4 @@ markdown==3.1.1 git+git://github.com/miracle2k/webassets#d1f3455e383446ca4ab0c644f326ee937e68e809 cssmin==0.2.0 libsass==0.19.3 +beautifulsoup4==4.8.1