今天来讲一下Django中自定义模板标签的使用,在此之前我需要先说一下在使用自定义模板标签的时候我的博客视图函数是怎么样的
因为博客除了为数不多的几个页面,其他页面都是有sidebar也就是的侧边栏的,所以我在所有页面的视图函数中都用了几乎同样的代码来查询侧边栏的数据,这就造成了严重的代码冗余,大忌!!!
我在研究了别人的源码后我发现,咦!这家伙的主页视图函数怎么只有一个ListView?那他的侧边栏怎么来的?
带着疑问我又看了他的前端部分,???里面有着如下代码
{% get_category_list as categories %}
这是啥子?
在询问度娘后才直到模板标签可以自定义,新知识GET!欧耶
感受到了自定义模板标签带来的便捷,我立马对博客进行改造
首先在blog app下新建一个templatetags文件夹(必须是这个名字) 在文件夹中新建
- __init_ _.py
- blog_tags.py # 可以自定义
init的作用想必就不用说了 在blog_tags.py中写入如下代码:
from django import template
from blog.models import Category
from django.db.models.aggregates import Count
from taggit.models import Tag
register = template.Library()
@register.simple_tag
def get_category_list():# 定义的模板标签方法
'''返回分类列表'''
return Category.objects.annotate(post_num=Count('article')).filter(post_num__gt=0)
模板标签定义好之后就可以去模板使用了
<!-- 必须先加载自定义模板标签文件 -->
{% load blog_tags %}
<!-- 文章分类 -->
<div class="card border-0 rounded-0 px-3 mb-2 mb-md-3" id="category-card">
<div class="card-header bg-white px-0">
<strong><i class="fa fa-book mr-2 f-17"></i>文章分类</strong>
</div>
<!-- 将返回的值命名为categories-->
{% get_category_list as categories %}
<ul class="list-group list-group-flush f-16">
{% for each in categories %}
<li class="list-group-item d-flex justify-content-between align-items-center pr-2 py-2">
<a class="category-item" href="{% url 'category' each.category_name %}" title="查看【{{ each.category }}】分类下所有文章">{{ each.category }}</a>
<span class="badge text-center" title="当前分类下有{{ each.post_num }}篇文章">{{ each.post_num }}</span>
</li>
{% endfor %}
</ul>
</div>
还可以给自定义标签传参,参数跟在标签后就可以了,比如
{% get_category_list category as categories %}
后端接收
def get_category_list(category):
传参可以进行分类显示之类的,很方便
这样一来,我首页的视图函数也就只有ListView了,美滋滋
class IndexView(generic.ListView):
model = Article
template_name = 'index.html'
context_object_name = 'posts'
paginate_by = 5
什么?不知道什么叫Listview?我们下次见。
最后修改于2020年3月20日 21:10
©允许规范转载
Django Python版权声明:如无特殊说明,文章均为本站原创,转载请注明出处
本文链接:https://www.yangyingqi.com/15.html