Fix slice filter appending fill_with when items divide evenly

When the iterable length is evenly divisible by the slice count,
`slices_with_extra` is 0, making the condition
`slice_number >= slices_with_extra` true for all slices. This
incorrectly appends fill_with to every slice.

For example, `[1,2,3,4]|slice(4, 'foo')` produced
`[[1, 'foo'], [2, 'foo'], [3, 'foo'], [4, 'foo']]` instead of
`[[1], [2], [3], [4]]`.

Fix by also checking that `slices_with_extra` is non-zero before
appending fill_with.

Fixes #2118

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Friday 2026-02-18 04:54:32 +00:00
parent 5ef70112a1
commit 3a1dcbef65
2 changed files with 6 additions and 1 deletions

View File

@ -1089,7 +1089,7 @@ 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 slices_with_extra and slice_number >= slices_with_extra:
tmp.append(fill_with)
yield tmp

View File

@ -78,6 +78,11 @@ class TestFilter:
"[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]"
)
def test_slice_evenly_divisible(self, env):
tmpl = env.from_string("{{ foo|slice(4, 'X')|list }}")
out = tmpl.render(foo=[1, 2, 3, 4])
assert out == "[[1], [2], [3], [4]]"
def test_escape(self, env):
tmpl = env.from_string("""{{ '<">&'|escape }}""")
out = tmpl.render()