django国际化日历并使用单个字符日名称

时间:2011-07-28 15:42:08

标签: python django

我有两个问题,我最近建立了一个django自定义模板标签,在调用时显示日历。我目前面临两个不确定如何解决的问题,

  • 如何将日期名称显示为单个字符(S,M,T,..等)我找到了返回的calendar.day_abbr(SAT,MON..etc)
  • 我的网站正在使用多种语言,我想知道如何根据查看语言显示它们。我尝试使用LocaleTextCalendar()但没有任何运气。

    来自django导入模板

    导入日历

    来自django.conf导入设置

    register = template.Library()

    def calendar_parser(解析器,令牌):     “””         日历解析器将处理验证参数并将它们传递给上下文     “””     尝试:         tag_name,year,month,entries,as_,resolve_tag = token.split_contents()     除了ValueError:         raise template.TemplateSyntaxError,“%r tag需要六个参数”%token.contents.split()[0]     return calendar_node(year,month,entries,resolve_tag)

    class calendar_node(template.Node):     “””     处理模板中的特定节点。安静地失败。     “”“

    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_year, 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.tag(“calendar_view”,calendar_parser)

1 个答案:

答案 0 :(得分:1)

calendar.weekheader(n)

  

返回包含缩写的工作日名称的标头。 n 指定一个工作日的字符宽度。

因此,对于n = 1,将返回单个字符缩写。