Login

Django Incremental Counter Tag

Author:
gwrtheyrn
Posted:
December 1, 2011
Language:
Python
Version:
1.3
Score:
1 (after 1 ratings)

Counter tag. Can be used to output and increment a counter.

For usage, see docstring in the code.

This is the first complete tag that I've implemented, I hope that there are no bugs and that it's thread safe.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
@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_var %} to access the last counter variable without incrementing

    """
    try:
        tag_name, reset = token.contents.split(None, 1)
    except ValueError:
        reset = False
    else:
        if reset == 'reset':
            reset = True
    return CounterNode(reset)

class CounterNode(template.Node):
    def __init__(self, reset):
        self.reset = reset

    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 

        # Set the counter_var context variable
        context['counter_var'] = context.render_context['counter']

        # When resetting, we don't want to return anything
        if self.reset:
            return ''

        # Increment counter. This does not affect the return value!
        context.render_context['counter'] += 1

        # Return counter number
        return context['counter_var']

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

nishant1630 (on October 25, 2013):

@gwrtheyrn: I am quite new to Django and I found above code pretty useful for one of my purpose, but I don't want to display value of count on page, just want to keep it for increment purpose. Can we avoid it somehow not to display?

Thanks in advance..

Nishant

#

Please login first before commenting.