Last active
October 11, 2023 05:01
-
-
Save sonus21/0ebd1b894ec837c8f8b2 to your computer and use it in GitHub Desktop.
Django counter tag, can generate counter in case of single or multiple for loop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Adapted from https://djangosnippets.org/snippets/2619/ | |
@register.tag(name='counter') | |
def do_counter(parser, token): | |
""" | |
Counter tag. Can be used to output and increment a counter. | |
Usage: | |
- {% counter %} to output and post-increment the counter variable | |
- {% counter reset %} to reset the counter variable to 1 | |
- {% counter last %} to access the last counter variable without incrementing | |
""" | |
try: | |
tag_name, request = token.contents.split(None, 1) | |
except ValueError: | |
request = None | |
if request == 'reset': | |
reset = True | |
last = False | |
elif request == 'last': | |
last = True | |
reset = False | |
else: | |
reset = False | |
last = False | |
return CounterNode(reset, last) | |
class CounterNode(template.Node): | |
def __init__(self, reset, last): | |
self.reset = reset | |
self.last= last | |
def render(self, context): | |
# When initializing or resetting, set counter variable in render_context to 1. | |
if self.reset or ('counter' not in context.render_context): | |
context.render_context['counter'] = 1 | |
# When resetting, we don't want to return anything | |
if self.reset: | |
return '' | |
# When ask for old, return previous count | |
if self.last: | |
return context.render_context['counter']-1 | |
counter = context.render_context['counter'] | |
# Increment counter | |
context.render_context['counter'] += 1 | |
# Return counter | |
return counter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for response. I try to implement it but I didn't be able to reset the counter in django.
I appreciate that you put more instructions.