Skip to content

Instantly share code, notes, and snippets.

@akisute
Created February 20, 2010 09:22
Show Gist options
  • Save akisute/309606 to your computer and use it in GitHub Desktop.
Save akisute/309606 to your computer and use it in GitHub Desktop.
""" My tag library. """
from django.template import Node, NodeList, Template, Context, Variable
from django.template import TemplateSyntaxError, VariableDoesNotExist, BLOCK_TAG_START, BLOCK_TAG_END, VARIABLE_TAG_STAR
T, VARIABLE_TAG_END, SINGLE_BRACE_START, SINGLE_BRACE_END, COMMENT_TAG_START, COMMENT_TAG_END
from django.template import get_library, Library, InvalidTemplateLibrary
from django.conf import settings
from django.utils.encoding import smart_str, smart_unicode
from django.utils.itercompat import groupby
from django.utils.safestring import mark_safe
register = Library()
class NowWithDeltaNode(Node):
def __init__(self, format_string, delta):
self.format_string = format_string
self.delta = delta
def render(self, context):
from datetime import datetime, timedelta
from django.utils.dateformat import DateFormat
td = timedelta(int(self.delta)) if self.delta else timedelta(0)
df = DateFormat(datetime.now() + td)
return df.format(self.format_string.strip('"'))
#@register.tag
def now_with_delta(parser, token):
"""
Displays the date, formatted according to the given string with delta.
Uses the same format as PHP's ``date()`` function; see http://php.net/date
for all the possible values.
Sample usage::
Yesterday is {% now_with_delta "jS F Y H:i" -1 %}
Tomorrow is {% now_with_delta "jS F Y H:i" 1 %}
"""
bits = token.split_contents()
if len(bits) < 2:
raise TemplateSyntaxError, "%r statement takes at least 1 argument" % bits[0]
format_string = bits[1]
delta = None if len(bits) == 2 else bits[2]
return NowWithDeltaNode(format_string, delta)
now_with_delta = register.tag(now_with_delta)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment