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 Sep 8, 2022
1 parent 21a3ad5 commit 2029673
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions wagtail_footnotes/blocks.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from collections import defaultdict
import re

from django.core.exceptions import ValidationError
Expand Down Expand Up @@ -33,6 +34,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 @@ -46,15 +48,20 @@ 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>'

return mark_safe(FIND_FOOTNOTE_TAG.sub(replace_tag, html))

Expand All @@ -67,7 +74,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 2029673

Please sign in to comment.