Skip to content

Commit

Permalink
Merge pull request #8445 from cfpb/fix/link-markup-whitespace
Browse files Browse the repository at this point in the history
Fix extra whitespace in some link markup cases
  • Loading branch information
chosak authored May 31, 2024
2 parents 0576fae + 0afc93b commit 494f3d0
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
16 changes: 16 additions & 0 deletions cfgov/core/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,3 +261,19 @@ def test_link_button(self):
expected_tag = BeautifulSoup(expected_html, "html.parser")

self.assertEqual(add_link_markup(tag, path), str(expected_tag))

def test_link_with_whitespace_in_text(self):
url = "https://example.com"
tag = f'<a href="{url}">\nClick <strong>here</strong> now! </a>'
path = "/about-us/blog/"

expected_html = (
f'<a class="a-link a-link--icon" href="{url}">'
'<span class="a-link__text">'
"Click <strong>here</strong> now!</span> "
f"{self.external_link_icon}"
"</a>"
)

expected_tag = BeautifulSoup(expected_html, "html.parser")
self.assertEqual(add_link_markup(tag, path), str(expected_tag))
15 changes: 14 additions & 1 deletion cfgov/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from django.template.defaultfilters import slugify

from bs4 import BeautifulSoup
from bs4 import BeautifulSoup, NavigableString

from core.templatetags.svg_icon import svg_icon

Expand Down Expand Up @@ -195,6 +195,19 @@ def add_link_markup(tag, request_path):
tag.clear()
tag.append(span)

# Whether we used an existing text span with a-link__text or added a
# new one, we want to make sure that the link text doesn't include any
# wrapping whitespace, otherwise it'll be incorrectly underlined.
#
# This fixes tags like <a> text with surrounding whitespace </a> or
# tags like <a> text with <strong>other</strong> tag </a> but not tags
# like <a> text with <strong>other tag with whitespace </strong></a>.
if span.contents:
if isinstance(span.contents[0], NavigableString):
span.contents[0] = NavigableString(span.contents[0].lstrip())
if isinstance(span.contents[-1], NavigableString):
span.contents[-1] = NavigableString(span.contents[-1].rstrip())

tag.append(" ")
tag.append(icon_soup)

Expand Down

0 comments on commit 494f3d0

Please sign in to comment.