Login

Template tag and filter for displaying number of years since

Author:
tgandor
Posted:
March 22, 2014
Language:
Python
Version:
1.6
Tags:
template now since years
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. get_querystring template tag by skam 1 month, 2 weeks ago
  2. Fuzzy Date Diff Template Filter by zain 6 years ago
  3. BirthYearField by steve_cassidy51 7 years, 3 months ago
  4. SelectDateWidget with format: day, month, year by zenx 5 years, 3 months ago
  5. FixedEmailMessage by buriy 7 years ago

Comments

Please login first before commenting.