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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.