{% regroup %} 标签渲染文章归档

229 阅读1分钟

regroup

官方文档:

docs.djangoproject.com/en/1.11/ref… 

regroup 这个标签的作用便是:用一个共同的属性重新组合一个类似的对象列表

在做归档功能之前,我们能从表中查询出来的数据大概为:

现在,我们需要将这26条数据,按照年、月渲染成列表:

具体实现

显然,这个公共属性便是 pub_time,即发布日期

由于需要按照年、月进行归档,所以我们需要两次 regroup:

按照年 regroup:

{% regroup posts by pub_time|date:"Y" as pub_time_year %}

按照月 regroup:

{% regroup pub_time.list by pub_time|date:"m" as pub_time_month %}

完整示例:

1. 将 pub_time 按照年 regroup,得到 pub_time_year;(此时它为按年分组的 POSTS 数组对象)

2. 循环 pub_time_year,将循环的每一个 item 按月 regroup,得到 pub_time_month

3. 继续循环 pub_time_month,它便是最终待渲染的文章列表了;

<div class="post-content">
    <hr>
    {% regroup posts by pub_time|date:"Y" as pub_time_year %}
    {% for pub_time in pub_time_year %}
        <h4>{{ pub_time.grouper }}</h4>
        <hr>
        {% regroup pub_time.list by pub_time|date:"m" as pub_time_month %}
        {% for pub_time in pub_time_month %}
            <h5>{{ pub_time.grouper }} »</h5>
            <div class="list-group">
                <ul class="posts">
                {% for post in pub_time.list %}
                    <li>
                        <a href="{{ post.get_absolute_url }}">{{ post.title }}</a>
                            »
                            <span>{{ post.pub_time | date:"Y-m-d" }}</span>
                    </li>
               {% endfor %}
               </ul>
          </div>
        {% endfor %}
        {% if forloop.last == False %}
          <hr>
        {% endif %}
    {% endfor %}
</div>