标签:load 视图 .lib context rom end ftime cut 定义
流程:
1 #my_filter.py 2 from django import template 3 register = template.Library() 4 5 def greet(value,world): 6 return value + world 7 8 #注册 9 register.filter(‘greet‘,greet)
# 使用装饰器
1 from django import template 2 register = template.Library() 3 4 @register.filter(‘greet‘) #可为过滤器命名 5 def greet(value,world): 6 return value + world
1 #settings.py 2 ‘‘‘ 3 INSTALLED_APPS = [ 4 ... 5 ‘front‘ #添加app 6 ] 7 ‘‘‘
1 <!--加载过滤器--> 2 {% load my_filter %} 3 <!DOCTYPE html> 4 ... 5 <body> 6 {{ value|greet:‘欢迎‘ }} 7 </body> 8 </html>
例子:
1 from django import template 2 from datetime import datetime 3 4 register = template.Library() 5 6 @register.filter 7 def time_since(value): 8 ‘‘‘ 9 :param value:输入的时间 10 :return:输入的时间距离现在的时间间隔(可用于发布动态后显示距离当前时间的时间间隔) 11 1、如果时间间隔小于1分钟,显示‘刚刚’; 12 2、如果大于1分钟小于1小时,显示‘xx分钟前’; 13 3、如果大于1小时小于24小时,显示‘xx小时前’; 14 4、如果大于24小时小于30天,显示‘xx天前’; 15 5、否则显示具体时间:xxxx/xx/xx xx/xx; 16 ‘‘‘ 17 if not isinstance(value,datetime): 18 return value 19 now = datetime.now() 20 # timedelay.total_seconds() 定义持续时间内的总秒数 21 timestamp = (now - value).total_seconds() 22 if timestamp < 60: 23 return ‘刚刚‘ 24 elif timestamp >= 60 and timestamp < 60*60: 25 minutes = int(timestamp/60) 26 return ‘%s分钟前‘ % minutes 27 elif timestamp >= 60*60 and timestamp < 60*60*24: 28 hours = int(timestamp/60/60) 29 return ‘%s小时前‘% hours 30 elif timestamp >= 60*60*24 and timestamp < 60*60*24*30: 31 days = int(timestamp/60/60/24) 32 return ‘%s天前‘% days 33 else: 34 return value.strftime("%Y/%m%d %H:%M")
1 from django.shortcuts import render 2 from datetime import datetime 3 def index(request): 4 # content = input(‘输入你要发表的内容:‘) 5 context = { 6 ‘value‘: datetime(year=2019,month=1,day=25,hour=10,minute=20) 7 } 8 return render(request,‘index.html‘,context)
1 {% load my_filter %} 2 <!DOCTYPE html> 3 <html lang="en"> 4 <head> 5 <meta charset="UTF-8"> 6 <title>Title</title> 7 <style> 8 body{ 9 background: aliceblue; 10 } 11 </style> 12 </head> 13 <body> 14 {{ value|time_since }} 15 </body> 16 </html>
标签:load 视图 .lib context rom end ftime cut 定义
原文地址:https://www.cnblogs.com/liqiongming/p/10321698.html