From 7653f1523c76350e53811851997829c13326e7c9 Mon Sep 17 00:00:00 2001 From: Laura Beaufort Date: Thu, 18 Mar 2021 19:11:59 -0400 Subject: [PATCH] Fix filter when results have { or } --- fec/home/templatetags/filters.py | 13 ++++++++++--- fec/home/tests/test_filters.py | 23 +++++++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) create mode 100644 fec/home/tests/test_filters.py diff --git a/fec/home/templatetags/filters.py b/fec/home/templatetags/filters.py index 6c0b6fe626..1cfced0cd1 100644 --- a/fec/home/templatetags/filters.py +++ b/fec/home/templatetags/filters.py @@ -68,15 +68,22 @@ def web_app_url(path): @register.filter() def highlight_matches(text): - """Replaces the highlight markers with span tags for digitalgov search results""" - highlighted_text = text.replace('\ue000', '').replace('\ue001', '') + """ + Replaces the highlight markers with span tags for digitalgov search results. + Because format_html uses str.format, remove { and } because they are special characters. + """ + cleaned_text = text.replace("{", "").replace("}", "") + highlighted_text = cleaned_text.replace( + "\ue000", '' + ).replace("\ue001", "") + return format_html(highlighted_text) @register.filter(name='splitlines') def splitlines(value): """ - Returns the value turned into a list. + Returns the value turned into a list. """ return value.splitlines() diff --git a/fec/home/tests/test_filters.py b/fec/home/tests/test_filters.py new file mode 100644 index 0000000000..1bc238c6ed --- /dev/null +++ b/fec/home/tests/test_filters.py @@ -0,0 +1,23 @@ +from django.test import TestCase + +from home.templatetags.filters import highlight_matches + + +class TestFilters(TestCase): + + def test_highlight_matches(self): + text = '\ue000Highlighted\ue001 results' + highlighted_text = highlight_matches(text) + self.assertEqual( + highlighted_text, + 'Highlighted results' + ) + + def test_highlight_matches_with_brackets(self): + """highlight_matches should remove { and } from results""" + text = '\ue000Highlighted\ue001 {results}' + highlighted_text = highlight_matches(text) + self.assertEqual( + highlighted_text, + 'Highlighted results' + )