diff --git a/CHANGES.rst b/CHANGES.rst index 338dc9966..32b51f82f 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -13,6 +13,8 @@ Unreleased - Use modern packaging metadata with ``pyproject.toml`` instead of ``setup.cfg``. :pr:`1793` - Use ``flit_core`` instead of ``setuptools`` as build backend. +- Fix ``slice`` filter incorrectly appending ``fill_with`` value when the + iterable length is evenly divisible by the slice count. :issue:`2118` Version 3.1.6 diff --git a/src/jinja2/filters.py b/src/jinja2/filters.py index c46e20c10..1d87cc1dd 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 + 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..7804b656a 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -78,6 +78,16 @@ def test_slice(self, env): "[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]" ) + def test_slice_evenly_divisible(self, env): + """fill_with should not be appended when items divide evenly.""" + tmpl = env.from_string("{{ foo|slice(4, 'X')|list }}") + out = tmpl.render(foo=[1, 2, 3, 4]) + assert out == "[[1], [2], [3], [4]]" + + tmpl = env.from_string("{{ foo|slice(2, 'X')|list }}") + out = tmpl.render(foo=[1, 2, 3, 4, 5, 6]) + assert out == "[[1, 2, 3], [4, 5, 6]]" + def test_escape(self, env): tmpl = env.from_string("""{{ '<">&'|escape }}""") out = tmpl.render()