#36186 closed New feature (fixed)

forloop should have an accessor for the total count of the loop

Reported by: Jonathan Ströbele Owned by: Jonathan Ströbele
Component: Template system Version: 5.1
Severity: Normal Keywords:
Cc: Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

The forloop has no way for accessing the total loop iteration count, though the ​length of the values being iterated is already known on the logic for building up the forloop variable.

I propose to expose this count on the forloop variable, i.e. like: forloop.total. I think it can be helpful to have this information available inside a loop if needed (this also the case for example in the ​Laravel/Blade loop variable):

{% for val in values %}
  {{ forloop.total }}
{% endfor %}

I prepared a patch here and can send it of as a PR if it's okay: ​https://github.com/stroebjo/django/commit/0a6233bcd9f2356a2b7b646ad4448ee313dc4d43

Change History (6)

comment:1 by Sarah Boyce, 20 months ago

Triage Stage: Unreviewed → Accepted
Type: Uncategorized → New feature

I suppose this is possible already with something like {{ forloop.counter|add:forloop.revcounter }}
I do however think this would be a nice addition, feels at the least more readable/discoverable and it's good to see that other frameworks have come to that conclusion

comment:2 by Sarah Boyce, 20 months ago

Has patch: unset
Owner: set to Jonathan Ströbele
Status: new → assigned

Once you submit a PR to the project, can you update the flags here? Note that it would need a .. versionchanged note and a release note :)

comment:3 by Jonathan Ströbele, 20 months ago

Hi thanks for the reply,

I noticed that Jinja2 also has this ​feature, they call it .length . Would that be more appropriate for Django as well? Like forloop.length or is .total fine (the other keys are named differently anyways).

Regarding the release:

  • I put it into the release of 5.1.7, is this fine?
  • I tried to unterstand how to markup the .. versionchanged, but here I'm not sure if I did this correctly regarding the forloop table.

I prepared the PR and sent it of, if I should change something please let me know! :)

​PR

comment:4 by Jonathan Ströbele, 20 months ago

Has patch: set

comment:5 by Sarah Boyce, 19 months ago

Triage Stage: Accepted → Ready for checkin

comment:6 by Sarah Boyce <42296566+sarahboyce@…>, 19 months ago

Resolution: → fixed
Status: assigned → closed

In 240421c7:

Fixed #36186 -- Added forloop.length variable within a template for loop.

Note: See TracTickets for help on using tickets.
Back to Top