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
and slice_number >= slices_with_extra
and slices_with_extra != 0
):
tmp.append(fill_with)

yield tmp
Expand Down
22 changes: 22 additions & 0 deletions tests/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,28 @@ def test_slice(self, env):
"[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]"
)

def test_slice_even_division_with_fill(self, env):
"""Regression test for #2118: fill_with should not add items when
the slice count evenly divides the iterable length."""
tmpl = env.from_string("{{ foo|slice(4, 'foo')|list }}")
out = tmpl.render(foo=[1, 2, 3, 4])
assert out == "[[1], [2], [3], [4]]"

def test_slice_even_division_no_fill(self, env):
tmpl = env.from_string("{{ foo|slice(2)|list }}")
out = tmpl.render(foo=[1, 2, 3, 4])
assert out == "[[1, 2], [3, 4]]"

def test_slice_uneven_with_fill(self, env):
tmpl = env.from_string("{{ foo|slice(2, 'x')|list }}")
out = tmpl.render(foo=[1, 2, 3])
assert out == "[[1, 2], [3, 'x']]"

def test_slice_uneven_five_items(self, env):
tmpl = env.from_string("{{ foo|slice(3, 'x')|list }}")
out = tmpl.render(foo=[1, 2, 3, 4, 5])
assert out == "[[1, 2], [3, 4], [5, 'x']]"

def test_escape(self, env):
tmpl = env.from_string("""{{ '<">&'|escape }}""")
out = tmpl.render()
Expand Down
Loading