from django import template from datetime import datetime, timedelta register = template.Library() class NakedDayNode(template.Node): def __init__(self, params, varname): self.params = params self.varname = varname def render(self, context): naked_date = datetime(year=self.params['year'], month=self.params['month'], day=self.params['day']) start = naked_date - timedelta(hours=12) end = naked_date + timedelta(hours=36) now = datetime.utcnow() is_naked = now > start and now < end if self.varname: context[self.varname] = is_naked return '' def do_naked_day(parser, token): """ Returns True or False if today is Naked CSS Day (2009-04-09ish) and spans ~48 hours. Optionally accepts ``year``, ``month``, and ``day`` values in case Naked CSS Day changes in the future. Optionally takes a template context with a variable containing that value, whose name is defined by the ``as`` clause. Usage:: {% is_naked_day [year:integer] [month:integer] [day:integer] as [varname] %} Example:: {% is_naked_day as is_naked %} {% if is_naked %} {% else %} {% endif %} Example with parameters:: {% is_naked_day month:4 day:9 as is_naked %} {% if is_naked %} {% else %} {% endif %} Additional information: For more information on Naked CSS Day and to add your site to the list: http://naked.dustindiaz.com/ """ params = { 'year': datetime.utcnow().year, 'month': 4, 'day': 9, } varname = None items = token.split_contents() for index, item in enumerate(items): if item == 'as': varname = items[index + 1] elif ':' in item: param, value = item.split(':') param, value = param.strip(), value.strip() if param in params: if value[0] == '"': value = value[1:-1] try: params[param] = int(value) except ValueError: raise template.TemplateSyntaxError( 'Parameter "%s" can only be an integer field.' % (param)) return NakedDayNode(params, varname) register.tag('is_naked_day', do_naked_day)