Created
October 8, 2012 02:03
-
-
Save niran/3850352 to your computer and use it in GitHub Desktop.
Django template tag for reversing date-based URLs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import template | |
from django.template import defaulttags, Parser, FilterExpression | |
from django.template.defaulttags import URLNode | |
register = template.Library() | |
class DateURLNode(URLNode): | |
def __init__(self, *args, **kwargs): | |
super(DateURLNode, self).__init__(*args, **kwargs) | |
self.date = self.args[0] | |
self.args = self.args[1:] | |
def render(self, context): | |
# Transform the date into kwargs as if the date parts were passed as | |
# string literals in the template. | |
date = self.date.resolve(context) | |
dummy_parser = Parser('') | |
self.kwargs['year'] = FilterExpression('"%s"' % date.strftime('%Y'), | |
dummy_parser) | |
self.kwargs['month'] = FilterExpression('"%s"' % date.strftime('%m'), | |
dummy_parser) | |
self.kwargs['day'] = FilterExpression('"%s"' % date.strftime('%d'), | |
dummy_parser) | |
return super(DateURLNode, self).render(context) | |
@register.tag | |
def date_url(parser, token): | |
'''A derivative of {% url %} that handles date based URLs. | |
The passed date will be passed as `year`, `month`, and `day` kwargs | |
to the {% url %} code.''' | |
url_node = defaulttags.url(parser, token) | |
return DateURLNode(url_node.view_name, url_node.args, url_node.kwargs, | |
url_node.asvar) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment