编写模板文件
首先编写tag
的模板,新建blog/templates/blog/tags.html
文件,假设传给模版的上下文里有一个tags
,代表所有标签,因此模板可以这么写
<ul>
{% for tag in tags %}
<li>
<h3 id="{
{ tag.name }}">{
{ tag.name }}</h3>
<ul>
{% for post in tag.post_set.all %}
<li><a href="{
{ post.get_absolute_url }}">{
{post.title }}</a></li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
这里将id
也设置为tag.name
,主要是设置锚(archors),方便快速跳转
由于tag
和post
是多对一关系,通过tag.post_set.all
,可以获取tag对应的所有文章
再使用UIKit3美化一下
{% extends 'blog/base.html' %}
{% block title %}Tags{% endblock %}
{% block body %}
<div class="uk-container">
<ul uk-accordion="multiple: true">
{% for tag in tags %}
<li class="uk-open">
<h3 class="uk-accordion-title" id="{
{ tag.name }}">{
{ tag.name }}</h3>