一,编写视图,返回文章列表
class ArchiveView(generic.ListView):
model = Article
template_name = 'blog/archive.html'
context_object_name = 'articles'
paginate_by = 200
二,前端
{% cache 3600 'cache_archive_html_tag' %}
<div class="col-lg-8">
<div class="card border-0 rounded-0 mb-3">
<div class="card-body f-16 archive">
{% regroup articles by create_date.year as year_list %}
<ul class="pl-4">
{% for article in year_list %}
<li>{{ article.grouper }} 年
{% regroup article.list by create_date.month as month_list %}
<ul class="pl-4">
{% for each in month_list %}
<li>{{ each.grouper }} 月 (共 {{ each.list|length }} 篇)
<ul class="pl-4">
{% for item in each.list %}
<li class="text-info">{{ item.create_date|date:'m-d' }} <a href="{{ item.get_absolute_url }}">{{ item.title }}</a></li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
{% endcache %}
三,用到的内置标签
1,cache
我们可以用cache模板标签来缓存模板的一个片段,要是用这个标签,首先要在模板的顶部位置添加{% load cache %}
模板标签{% cache %}将在设定的时间内,缓存标签块中包含的内容。它最少需要两个参数:缓存时间(以秒为单位)以及给缓存片段起的名称
{% load cache %}
{% cache 500 sidebar %}
… sidebar …
{% endcache %}
2,regroup
用对象间共有的属性重组列表
{% regroup %}有三个参数: 要重组的列表、用来分组的属性、结果列表的名字
eg:
可以使用{% regroup %}标签来给每个国家的城市分组:
{% regroup cities by country as country_list %}
- {% for country in country_list %}
- {{ country.grouper }}
- {% for city in country.list %}
- {{ city.name }}: {{ city.population }}
- {% endfor %}
- {% endfor %}
list - 此群组中所有项目的列表(例如,所有城市的列表,其中country =‘India’)
3,length
length:返回值的长度,适合于字符串和列表
4,date:根据给定的格式格式化日期。
{{ date|date:“Y-m-d H:i:s w” }}