Opened 9 days ago

Last modified 2 days ago

#36186 assigned New feature

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 (5)

comment:1 by Sarah Boyce, 8 days ago

Triage Stage: UnreviewedAccepted
Type: UncategorizedNew 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, 8 days ago

Has patch: unset
Owner: set to Jonathan Ströbele
Status: newassigned

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, 8 days 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, 8 days ago

Has patch: set

comment:5 by Sarah Boyce, 2 days ago

Triage Stage: AcceptedReady for checkin
Note: See TracTickets for help on using tickets.
Back to Top