Skip to content

Commit

Permalink
Initial attempt at allowing multiple references to the same footnote
Browse files Browse the repository at this point in the history
Previously this generated the same ``id`` attribute for every link in rich text for the same footnote, which breaks the "Back to content" link.
This generates a unique ``id`` for each footnote reference.
This commit does not expose these links on the front-end (yet), but at least the "back" link will point to a single id.
  • Loading branch information
jsma committed Jul 29, 2023
1 parent df367bc commit d7f9015
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions wagtail_footnotes/blocks.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import re

from collections import defaultdict

from django.core.exceptions import ValidationError
from django.utils.safestring import mark_safe
from wagtail.blocks import RichTextBlock
Expand All @@ -24,6 +26,7 @@ def __init__(self, **kwargs):
self.features = []
if "footnotes" not in self.features:
self.features.append("footnotes")
self.footnotes = {}

def replace_footnote_tags(self, value, html, context=None):
if context is None:
Expand All @@ -37,17 +40,22 @@ def replace_footnote_tags(self, value, html, context=None):
page = new_context["page"]
if not hasattr(page, "footnotes_list"):
page.footnotes_list = []
if not hasattr(page, "footnotes_references"):
page.footnotes_references = defaultdict(list)
self.footnotes = {
str(footnote.uuid): footnote for footnote in page.footnotes.all()
}

def replace_tag(match):
footnote_uuid = match.group(1)
try:
index = self.process_footnote(match.group(1), page)
index = self.process_footnote(footnote_uuid, page)
except (KeyError, ValidationError):
return ""
else:
return f'<a href="#footnote-{index}" id="footnote-source-{index}"><sup>[{index}]</sup></a>'
link_id = f"footnote-source-{index}-{len(page.footnotes_references[footnote_uuid])}"
page.footnotes_references[footnote_uuid].append(link_id)
return f'<sup id="{link_id}"><a href="#footnote-{index}">[{index}]</a></sup>'

# note: we return safe html
return mark_safe(FIND_FOOTNOTE_TAG.sub(replace_tag, html)) # noqa: S308
Expand All @@ -61,7 +69,6 @@ def render(self, value, context=None):

def render_basic(self, value, context=None):
html = super().render_basic(value, context)

return self.replace_footnote_tags(value, html, context=context)

def process_footnote(self, footnote_id, page):
Expand Down

0 comments on commit d7f9015

Please sign in to comment.