-
自定义过滤器
# myfilter.py from django import template # 实例化⾃定义过滤器注册对象 register = template.Library() # name代表在模板中使⽤的过滤器的名称 @register.filter(name='hello') def hello(value,arg): """ :param value: 传给hello过滤的值 :param arg: hello⾃带的参数 :return: """ return value + str(arg) @register.filter('time_ago') def time_ago(value): """ 定义⼀个距离当前时间多久之前的过滤器 :param value: :return: 1.如果时间间隔⼩于1分钟内,那么就显示刚刚 2.如果时间间隔⼤于1分钟⼩于1⼩时,那么就显示xx分钟前 3.如果时间间隔⼤于1⼩时⼩于24⼩时,那么就显示xx⼩时前 4.如果时间间隔⼤于24⼩时⼩于30天,那么就显示xx天前 5.如果时间间隔⼤于30天,那么就显示具体时间 """ if not isinstance(value, datetime.datetime): return value now = datetime.datetime.now() timestamp = (now - value).total_seconds() if timestamp < 60: return '刚刚' elif timestamp >= 60 and timestamp < 60 * 60: return '{}分钟前'.format(int(timestamp / 60)) elif timestamp >= 60 * 60 and timestamp < 60 * 60 * 24: return '{}⼩时前'.format(timestamp / 60 / 60) elif timestamp >= 60 * 60 * 24 and timestamp < 60 * 60 * 23 * 30: return '{}天前'.format(int(timestamp / 60 / 60 / 24)) else: return value.strftime('%Y-%m-%d %H:%M')
# myfilter.html {% load customfilter %} #加载⾃定义过滤器的模块 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{ name |hello:' how are you' }} #使⽤⾃定义过滤器 </body> </html>
Django——模板—自定义过滤器
猜你喜欢
转载自blog.csdn.net/piduocheng0577/article/details/105001350
今日推荐
周排行