mirror of
https://github.com/django/django.git
synced 2026-02-09 02:49:25 +08:00
[5.1.x] Fixed #36341 -- Preserved whitespaces in wordwrap template filter.
Regression in55d89e25f4. This work improves the django.utils.text.wrap() function to ensure that empty lines and lines with whitespace only are kept instead of being dropped. Thanks Matti Pohjanvirta for the report and fix. Co-authored-by: Natalia <124304+nessita@users.noreply.github.com> Backport of1e9db35836from main.
This commit is contained in:
committed by
Natalia
parent
0aa0224107
commit
09a1813cb8
@@ -54,10 +54,19 @@ def wrap(text, width):
|
||||
width=width,
|
||||
break_long_words=False,
|
||||
break_on_hyphens=False,
|
||||
replace_whitespace=False,
|
||||
)
|
||||
result = []
|
||||
for line in text.splitlines(True):
|
||||
result.extend(wrapper.wrap(line))
|
||||
for line in text.splitlines():
|
||||
wrapped = wrapper.wrap(line)
|
||||
if not wrapped:
|
||||
# If `line` contains only whitespaces that are dropped, restore it.
|
||||
result.append(line)
|
||||
else:
|
||||
result.extend(wrapped)
|
||||
if text.endswith("\n"):
|
||||
# If `text` ends with a newline, preserve it.
|
||||
result.append("")
|
||||
return "\n".join(result)
|
||||
|
||||
|
||||
|
||||
@@ -89,3 +89,44 @@ class FunctionTests(SimpleTestCase):
|
||||
"I'm afraid",
|
||||
wordwrap(long_text, 10),
|
||||
)
|
||||
|
||||
def test_wrap_preserve_newlines(self):
|
||||
cases = [
|
||||
(
|
||||
"this is a long paragraph of text that really needs to be wrapped\n\n"
|
||||
"that is followed by another paragraph separated by an empty line\n",
|
||||
"this is a long paragraph of\ntext that really needs to be\nwrapped\n\n"
|
||||
"that is followed by another\nparagraph separated by an\nempty line\n",
|
||||
30,
|
||||
),
|
||||
("\n\n\n", "\n\n\n", 5),
|
||||
("\n\n\n\n\n\n", "\n\n\n\n\n\n", 5),
|
||||
]
|
||||
for text, expected, width in cases:
|
||||
with self.subTest(text=text):
|
||||
self.assertEqual(wordwrap(text, width), expected)
|
||||
|
||||
def test_wrap_preserve_whitespace(self):
|
||||
width = 5
|
||||
width_spaces = " " * width
|
||||
cases = [
|
||||
(
|
||||
f"first line\n{width_spaces}\nsecond line",
|
||||
f"first\nline\n{width_spaces}\nsecond\nline",
|
||||
),
|
||||
(
|
||||
"first line\n \t\t\t \nsecond line",
|
||||
"first\nline\n \t\t\t \nsecond\nline",
|
||||
),
|
||||
(
|
||||
f"first line\n{width_spaces}\nsecond line\n\nthird{width_spaces}\n",
|
||||
f"first\nline\n{width_spaces}\nsecond\nline\n\nthird\n",
|
||||
),
|
||||
(
|
||||
f"first line\n{width_spaces}{width_spaces}\nsecond line",
|
||||
f"first\nline\n{width_spaces}{width_spaces}\nsecond\nline",
|
||||
),
|
||||
]
|
||||
for text, expected in cases:
|
||||
with self.subTest(text=text):
|
||||
self.assertEqual(wordwrap(text, width), expected)
|
||||
|
||||
Reference in New Issue
Block a user