The pelican-plugins/ directory is gitignored, so moved the plugin to lib/ which is tracked. Updated PLUGIN_PATHS to include lib/. This plugin provides the strip_anchors Jinja2 filter that removes TOC divs and toc-backref anchor links from article summaries on the homepage, preventing broken anchor links in excerpts.
43 lines
1.1 KiB
Python
43 lines
1.1 KiB
Python
"""
|
|
Pelican plugin to strip Table of Contents and anchor links from article summaries.
|
|
|
|
This prevents TOC links and heading anchor links with invalid anchors
|
|
from appearing on the homepage.
|
|
"""
|
|
from pelican import signals
|
|
import re
|
|
|
|
|
|
def strip_anchors(text):
|
|
"""Jinja2 filter to strip TOC and anchor links from HTML text."""
|
|
if not text:
|
|
return text
|
|
|
|
# Remove the entire <div class="contents"> ... </div> block
|
|
text = re.sub(
|
|
r'<div\s+class="contents[^"]*"[^>]*>.*?</div>',
|
|
'',
|
|
text,
|
|
flags=re.DOTALL | re.IGNORECASE
|
|
)
|
|
|
|
# Remove anchor links from headings
|
|
# Converts <a class="toc-backref" href="#id1">text</a> to just text
|
|
text = re.sub(
|
|
r'<a[^>]*class="[^"]*toc-backref[^"]*"[^>]*>(.*?)</a>',
|
|
r'\1',
|
|
text,
|
|
flags=re.DOTALL | re.IGNORECASE
|
|
)
|
|
|
|
return text
|
|
|
|
|
|
def add_filter(pelican):
|
|
"""Add the strip_anchors filter to Jinja2."""
|
|
pelican.env.filters.update({'strip_anchors': strip_anchors})
|
|
|
|
|
|
def register():
|
|
"""Register the plugin with Pelican."""
|
|
signals.generator_init.connect(add_filter)
|