1.在app下创建templatetags文件夹 , [过滤器名]文件
├── templatetags
│ ├── __init__.py
│ └── addjpg.py
2.addjpg.py
from django import template
register = template.Library()
def adfjpg(value, word='.jpg'):
# 最多接受两个参数
# 第一个参数为被过滤的参数
return value + word
register.filter('addjpg', adfjpg)
3. settings中注册过滤器文件名
INSTALLED_APPS = [
'blog',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog.templatetags.addjpg', # <--------
]
4.template中
在load中导入过滤器名
{% load addjpg %}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<h1>{{ value | addjpg }}</h1>
</body>
</html>
5.举例(时间间隔过滤器)
def time_before(value):
'''
时间处理过滤器
1.如果时间间隔小于一分钟, 返回刚刚
2.如果时间间隔大于等于一分钟,小于一小时, 返回xx分钟前
3.如果时间间隔大于等于一小时,小于一天, 返回xx小时前
4.如果时间间隔大于等于一天,小于30天, 返回xx天前
5.否则返回
2020/3/3 21:42
'''
if not isinstance(value ,datetime):
return value
now = datetime.now()
timestamp = (now - value).total_seconds()
if timestamp < 60:
return '刚刚'
elif timestamp >= 60 and timestamp < 60*60:
minutes = timestamp // 60
return '%d分钟前' % minutes
elif timestamp >= 60*60 and timestamp < 60*60*24:
hours = timestamp // (60*60)
return '%d小时前' % hours
elif timestamp >= 60*60*24 and timestamp < 60*60*24*30:
days = timestamp // (60*60*24)
return '%d天前' % days
else:
return value.strftime('%Y/%m/%d %H:%M')