重新组合石斑鱼

时间:2012-10-20 19:19:51

标签: django templates

我已阅读this,但我还有一个问题:如何在模板中重命名country.grouper?我' group'星期几 - week_days.grouper,它像1,2,3等。但我想在模板中更改它 - 星期日,星期一等。怎么做?

1 个答案:

答案 0 :(得分:1)

custom template tag应该可以帮到你。必须将其放入文件中,例如您的应用中的my_custom_filters.py名为templatetags:

的文件夹
from django import template
register = template.Library()

def get_weekday(value):
    """returns the weekday for the given number - 0 indexed"""
    wd_list = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
    return wd_list[int(value)]

此自定义过滤器将按如下方式使用:

{% load my_custom_filters %}

{% regroup day by weekdays as weekday_list %}

<ul>
{% for day in weekday_list %}
    <li>{{ day.grouper|get_weekday }}
    <ul>
        {% for item in day.list %}
          <li>{{ item.name }}: {{ item.population }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>

如果您使用日期对象,可以使用内置date模板标记将日期转换为相应的工作日:

{% regroup day by weekdays as weekday_list %}

<ul>
{% for day in weekday_list %}
    <li>{{ day.grouper|date:"w" }}
    <ul>
        {% for item in day.list %}
          <li>{{ item.name }}: {{ item.population }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>