Login

counter templatetag

Author:
bcurtu
Posted:
November 12, 2009
Language:
Python
Version:
1.1
Score:
1 (after 1 ratings)

The counter initializes the variable to 0, and next it increments one by one:

{% load counter_tag %}
{% for pet in pets %}
    {% if pet.is_cat %}
        {% counter cats %}
    {% else %}
        {% counter dogs %}
    {% endif %}
{% endfor %}
# cats: {{cats}}
# dogs: {{dogs}}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django import template

register = template.Library()

@register.tag(name='counter')
def do_counter(parser, token):
    try:
        tag_name, args = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError("'counter' node requires a variable name.")
    return CounterNode(args)

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

    def render(self, context):
        try:
            var = template.resolve_variable(self.varname, context)
        except:
            var = 0
        deep = len(context.dicts)-1
        context.dicts[deep][self.varname] = var+1
        return ''

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

Please login first before commenting.