通过重写python calendar模块的HTMLCalendar类可以快速的定制自己需要Web日历。需要改写的地方不多,替换一下原来的css就ok了,month_name,day_abbr 这两个函数注意改写一下。Tornado默认会自动转义模板中的内容,你可以使用{% raw %}指令来输出不转义的内容。
如:{% raw cal %}
import calendar
import datetime
class MyCalendar(calendar.HTMLCalendar):
def lastmonth(self, theyear, themonth):
'''上个月的最后一天'''
first = datetime.date(day=1, month=themonth, year=theyear)
lastMonth = first - datetime.timedelta(days=1)
return lastMonth.strftime("/log/%Y-%m/-%d")
def nextmonth(self, theyear, themonth):
'''下个月的第一天'''
last = datetime.date(day=calendar.mdays[themonth], month=themonth, year=theyear)
nextMonth = last + datetime.timedelta(days=1)
return nextMonth.strftime("/log/%Y-%m/-%d")
def formatday(self, day, weekday):
if day == 0:
#加入td的css
return ' ' # day outside month
else:
return '%d ' % (day, day)
def formatweek(self, theweek):
s = ''.join(self.formatday(d, wd) for (d, wd) in theweek)
return '%s ' % s
def formatweekday(self, day):
return '%s ' % calendar.day_abbr[day] #day_abbr 改为 calendar.day_abbr
def formatweekheader(self):
s = ''.join(self.formatweekday(i) for i in self.iterweekdays())
#加入th的css
return '%s ' % s
def formatmonthname(self, theyear, themonth, withyear=True):
if withyear:
s = '%s %s' % (calendar.month_name[themonth], theyear) #month_name 改为 calendar.month_name
else:
s = '%s' % calendar.month_name[themonth] #month_name 改为 calendar.month_name
#加入标题栏的css
return '\
←\
→\
%s ' % (self.lastmonth(theyear, themonth),self.nextmonth(theyear, themonth),s)
def formatmonth(self, theyear, themonth, withyear=True):
v = ['']
a = v.append
a('')
a('\n')
a(self.formatmonthname(theyear, themonth, withyear=withyear))
a('\n')
a(self.formatweekheader())
a('\n')
for week in self.monthdays2calendar(theyear, themonth):
a(self.formatweek(week))
a('\n')
a('
')
a('\n')
return ''.join(v)
c = MyCalendar(calendar.SUNDAY)
chunk=c.formatmonth(2007, 7)
f=open("c.html","w+")
f.write(chunk)
f.close