django internationalizing a calendar and using single character day name
I have two questions, I've recently built a django custom templatetag which displays a calendar when called. Am currently facing two issues which am not sure how to resolve,
- How do I display day names as single character (S, M, T,..etc) I found calendar.day_abbr which returns (SAT, MON..etc)
My site is being used on several languages and I was wondering how do I get them to display as per viewing language. I tried using LocaleTextCalendar() but without any luck.
from django import template
import calendar
from django.conf import settings
register = template.Library()
def calendar_parser(parser, token): """ calendar parser will handle validating the parameters and passing them on to the context """ try: tag_name, year, month, entries, as_, resolve_tag = token.split_contents() except ValueError: raise template.TemplateSyntaxError, "%r tag requires six arguments" % token.contents.split()[0] return calendar_node(year, month, entries, resolve_tag)
class calendar_node(template.Node): """ Process a particular node in the template. Fail silently. """
def __init__(self, year, month, entries, resolve_tag): try: self.year = template.Variable(year) self.month = template.Variable(month) self.entries = template.Variable(entries) #resolved strings self.resolve_tag = resolve_tag except ValueError: raise template.TemplateSyntaxError def render(self, context): try: # FIRST_DAY_OF_WEEK beginning of the week, django setting cal = calendar.LocaleTextCalendar(settings.FIRST_DAY_OF_WEEK, 'ar') # render calendar header context['week_header'] = [day for day in calendar.day_name] # Get the variables from the context so the method is thread-safe. my_entries = self.entries.resolve(context) my_year = self.year.resolve(context) my_month = self.month.resolve(context) month_days = cal.itermonthdays(my_yea开发者_如何学运维r, my_month) lst = [[]] week = 0 # make month lists containing list of days for each week # each day tuple will contain list of entries and 'current' indicator for day in month_days: entries = current = False # are there entries for this day; current day? lst[week].append((day, my_entries, current)) if len(lst[week]) == 7: lst.append([]) week += 1 # assign variable to context as resolve_tag context[self.resolve_tag] = lst return '' except ValueError: return except template.VariableDoesNotExist: raise template.TemplateSyntaxError
Register the template tag so it is available to templates
register.tag("calendar_view", calendar_parser)
calendar.weekheader(n)
Return a header containing abbreviated weekday names. n specifies the width in characters for one weekday.
Thus for n=1 will return single character abbreviations.
精彩评论