Django模版过滤器是一个非常有用的功能,它允许我们在模版中处理数据。过滤器看起来像这样:{{ name|lower }},这将把变量name的值转换为小写。
1,创建应用
python manage.py startapp app5
2,注册应用
Test/Test/settings.py
3,添加应用路由
Test/Test/urls.py
示例
4,添加视图函数
Test/app5/views.py
from django.shortcuts import render
# Create your views here.
import datetime
def filter(request):
str1 = 'abcdefg'
str2 = 'ABCDEFGHIJKLMNO'
str3 = '123456789'
time_str = datetime.datetime.now()
return render(request, '5/filter.html', {'str1':str1, 'str2':str2, 'str3':str3, 'time_str':time_str})
5,添加路由地址
Test/app5/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('filter', views.filter, name='filter'),
]
6,添加html代码
Test/templates/5/filter.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
小写转大写: {{ str1|upper }} <br>
大写转小写: {{ str2|lower }} <br>
切片操作: {{ str3|slice:"2:4" }} <br>
时间格式化: {{ time_str|date:"Y-m-d G:i:s"}} <br>
</body>
</html>
7,访问页面
http://127.0.0.1:8000/app5/filter