Django Incremental Counter Tag

 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. counter templatetag by bcurtu 4 years, 5 months ago
  2. Increment a variable in a Template by sachingupta006 2 years ago
  3. Automate unique slugs by taojian 6 years, 4 months ago
  4. Counter model - run multiple persistent counters by simon 4 years, 10 months ago
  5. Incrementally Return CSV by davidblewett 6 years, 7 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

#

(Forgotten your password?)