diff --git a/src/jinja2/filters.py b/src/jinja2/filters.py index c46e20c10..27e5f0589 100644 --- a/src/jinja2/filters.py +++ b/src/jinja2/filters.py @@ -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 slices_with_extra > 0 + and slice_number >= slices_with_extra + ): tmp.append(fill_with) yield tmp diff --git a/tests/test_filters.py b/tests/test_filters.py index 4601469a6..afab3b655 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -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']]" + )