Login

Template tag and filter for displaying number of years since

Author:
tgandor
Posted:
March 22, 2014
Language:
Python
Version:
1.6
Score:
0 (after 0 ratings)

Because {% now "Y"|add:"-2005" %} - etc. doesn't work, you can use the above in your template like:

We have {{ 2000|since }} years of experience.

or:

Serving our customers with passion for more than {% years_since 2005 %} years.

 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
from django import template

# helper closure

def do_parse1arg(nodeCLS):
    """Parse tag name and 1 argument, return nodeCLS node."""
    def _do_parse1(parser, token):
        try:
            # split_contents() knows not to split quoted strings.
            tag_name, arg1 = token.split_contents()
        except ValueError:
            raise template.TemplateSyntaxError("%r tag requires 1 argument" % token.contents.split()[0])
        return nodeCLS(arg1)
    return _do_parse1

def since(start_year):
    from datetime import date
    return str(date.today().year - int(start_year))

class YearsSinceNode(template.Node):
    """Renders number of years since a specific year."""
    def __init__(self, start_year):
        self.years = since(start_year)
    def render(self, context):
        return self.years
register.tag('years_since', do_parse1arg(YearsSinceNode))
register.filter('since', since)

More like this

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

Comments

Please login first before commenting.