如何用数字显示月份名称?

如何用数字显示月份名称?

问题描述:

我有一个表示月份的数字,我想用月份名称替换它,日期过滤器不起作用:

I have a number represented month and i want to replace it with month name, date filter not working:

{{ monthnumber|date:"M" }}

我要放置两个链接-下个月和上个月,但是我只有一个月。

I want to place two links - next month and previous month, but i have only number of month.

如何做?

您将需要一个自定义模板过滤器,以将数字转换为月份名称。如果您使用标准库中的 calendar 模块,则非常简单:

You'll need a custom template filter to convert the number into a month name. Pretty simple if you use the calendar module from the standard library:

import calendar

@register.filter
def month_name(month_number):
    return calendar.month_name[month_number]

用法示例:
{{5 | month_name}}
将输出五月