Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/jinja2/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -1089,7 +1089,11 @@ def sync_do_slice(
end = offset + (slice_number + 1) * items_per_slice
tmp = seq[start:end]

if fill_with is not None and slice_number >= slices_with_extra:
if (
fill_with is not None
Comment on lines +1092 to +1093

Copilot AI Apr 3, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a regression test for the case where the input length divides evenly by the number of slices (so slices_with_extra == 0). With fill_with provided, this should not append any filler items (e.g., range(9)|slice(3, 'X') should yield [[0,1,2],[3,4,5],[6,7,8]]). This will ensure the bug fixed here doesn’t reappear, and should be covered in both sync and async filter tests if applicable.

Copilot uses AI. Check for mistakes.
and slices_with_extra > 0
and slice_number >= slices_with_extra
):
tmp.append(fill_with)

yield tmp
Expand Down
13 changes: 13 additions & 0 deletions tests/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -881,3 +881,16 @@ def test_filter_undefined_in_condexpr(self, env):

with pytest.raises(TemplateRuntimeError, match="No filter named 'f'"):
t2.render(x=42)

def test_slice_no_fill_with_even_division(self, env):
"""fill_with must not be appended when items divide evenly."""
t = env.from_string("{{ items|slice(4, 'X')|list }}")
assert t.render(items=[1, 2, 3, 4]) == "[[1], [2], [3], [4]]"
assert t.render(items=list(range(9))) == ("[[0, 1, 2], [3, 4, 5], [6, 7, 8]]")

def test_slice_fill_with_remainder(self, env):
"""fill_with should only be appended to shorter slices."""
t = env.from_string("{{ items|slice(3, 'X')|list }}")
assert t.render(items=list(range(10))) == (
"[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 'X']]"
)
Loading