Friday, July 11, 2008

"ago filter" / date tag filter - django snippet

from django import template
from StringIO import StringIO

register = template.Library()

@register.filter_function
def date_tag(path, tags):
"""
{{ "/recent/"|date_tag:"0,1,2,3" }}
"""
html = StringIO()
if path:
path = path.strip()
else:
path=""
tags = [x.strip() for x in tags.split(',')]
for tag in tags:
if tag == "0":
html.write('<a href="%s%s/">%s</a><br>' % (path,tag,"today"))
elif tag == "1":
html.write('<a href="%s%s/">%s</a><br>' % (path,tag,"yesterday"))
else:
html.write('<a href="%s%s/">%s</a><br>' % (path,tag,tag+" days ago"))
return html.getvalue()

===================================
usage:
1. put this code to app/templatetags directory, named tags.py
2. load tags into template: {% load tags %}
3. use filter

No comments: