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)