diff --git a/lacommunaute/forum/forms.py b/lacommunaute/forum/forms.py index c86796c6..24e6ee17 100644 --- a/lacommunaute/forum/forms.py +++ b/lacommunaute/forum/forms.py @@ -1,5 +1,3 @@ -import re - from django import forms from django.conf import settings from django.forms import CharField, CheckboxSelectMultiple, ModelMultipleChoiceField @@ -7,19 +5,7 @@ from lacommunaute.forum.models import Forum from lacommunaute.partner.models import Partner - - -def wrap_iframe_in_div_tag(text): - # iframe tags must be wrapped in a div tag to be displayed correctly - # add div tag if not present - - iframe_regex = r"((
)?(
)?)" - - for match, starts_with, ends_with in re.findall(iframe_regex, text, re.DOTALL): - if not starts_with and not ends_with: - text = text.replace(match, f"
{match}
") - - return text +from lacommunaute.utils.html import wrap_iframe_in_div_tag class ForumForm(forms.ModelForm): diff --git a/lacommunaute/utils/html.py b/lacommunaute/utils/html.py new file mode 100644 index 00000000..3d994973 --- /dev/null +++ b/lacommunaute/utils/html.py @@ -0,0 +1,14 @@ +import re + + +def wrap_iframe_in_div_tag(text): + # iframe tags must be wrapped in a div tag to be displayed correctly + # add div tag if not present + + iframe_regex = r"((
)?]*>.*?<\/iframe>(<\/div>)?)" + + for match, starts_with, ends_with in re.findall(iframe_regex, text, re.DOTALL): + if not starts_with and not ends_with: + text = text.replace(match, f"
{match}
") + + return text diff --git a/lacommunaute/utils/tests/tests_utils.py b/lacommunaute/utils/tests/tests_utils.py index b81f0ff5..2ff4d8ba 100644 --- a/lacommunaute/utils/tests/tests_utils.py +++ b/lacommunaute/utils/tests/tests_utils.py @@ -24,6 +24,7 @@ from lacommunaute.stats.models import ForumStat from lacommunaute.users.factories import UserFactory from lacommunaute.utils.date import get_last_sunday +from lacommunaute.utils.html import wrap_iframe_in_div_tag from lacommunaute.utils.math import percent from lacommunaute.utils.matomo import ( collect_forum_stats_from_matomo_api, @@ -707,3 +708,20 @@ class TestTheLastSunday: ) def test_the_last_sunday(self, day, expected_sunday): assert get_last_sunday(datetime(2024, 5, day)) == expected_sunday + + +class TestWrapIframeInDiv: + def test_wrap_iframe_in_div_tag(self): + inputs = [ + "", + "
", + "
", + "
", + ] + outputs = [ + "
", + "
", + "
", + "
", + ] + assert wrap_iframe_in_div_tag(" ".join(inputs)) == " ".join(outputs)