Properly handle out-of-order tag rewriting

pull/11961/head
Andy Chosak 2024-05-17 11:20:19 -04:00 zatwierdzone przez Matt Westcott
rodzic f98c4f8ae8
commit 83af49327b
2 zmienionych plików z 31 dodań i 12 usunięć

Wyświetl plik

@ -51,19 +51,24 @@ class TagRewriter:
for tag_type, attrs_list in attrs_by_tag_type.items()
]
offset = 0
matches_to_replace = []
for matches, replacements in zip(matches_by_tag_type.values(), replacements):
if not replacements:
continue
for match, replacement in zip(matches, replacements):
html = (
html[: match.start() + offset]
+ replacement
+ html[match.end() + offset :]
)
matches_to_replace.extend(zip(matches, replacements))
offset += len(replacement) - match.end() + match.start()
offset = 0
for match, replacement in sorted(
matches_to_replace, key=lambda match_to_replace: match_to_replace[0].start()
):
html = (
html[: match.start() + offset]
+ replacement
+ html[match.end() + offset :]
)
offset += len(replacement) - match.end() + match.start()
return html

Wyświetl plik

@ -192,11 +192,25 @@ This is another image: <embed embedtype="image" id="2" format="left" />
)
def test_expand_db_html_mixed_link_types(self):
html = '<a href="https://wagtail.org/">foo</a><a linktype="page" id="3">bar</a>'
result = expand_db_html(html)
self.assertEqual(
result,
('<a href="https://wagtail.org/">foo</a><a href="/events/">bar</a>'),
expand_db_html(
'<a href="https://wagtail.org/">foo</a>'
'<a linktype="page" id="3">bar</a>'
),
'<a href="https://wagtail.org/">foo</a><a href="/events/">bar</a>',
)
self.assertEqual(
expand_db_html(
'<a linktype="page" id="3">page</a>'
'<a linktype="document" id="1">document</a>'
'<a linktype="page" id="3">page</a>'
),
(
'<a href="/events/">page</a>'
'<a href="/documents/1/test.pdf">document</a>'
'<a href="/events/">page</a>'
),
)