模板一


模板
一、模板的组成
HTML代码+逻辑控制代码

二、逻辑控制代码的组成
1、变量(使用双大括号来引用变量)
语法:{{var_name}}
def current_time(req):
now = datetime.datetime.nowa()
return render(req,'current_datetime.html',{'current_date':now})

模板之深度查询,使用句点号——可以用于列表、字典

views内容:

class Animal():
def __init__(self,name,sex):
self.name = name
self.sex = sex
#模板之变量
def query(request):
l = ['a','b','c']
d = {"name":"kang","age":18,"sex":""}
c = Animal("alex","man") #实例一个对象
t = (1,2,3)
ti = datetime.datetime.now()
return render(request,"index.html",{"action":ti})
#return render(request,'index.html',locals())

#index.html文件内容

#使用键值对

这是通过键值对取值


hello {{ action.0 }}


hello {{ action.1 }}


hello {{ action.2 }}



取字典的值:{{ action.name }}


取类的值:{{ action.name }}


取元组的值:{{ action.0 }}


取元组的值:{{ action.1 }}


取元组的值:{{ action.2 }}



#得到的结果为
这是通过键值对取值
hello 1
hello 2
hello 3
取字典的值:
取类的值:
取元组的值:1
取元组的值:2
取元组的值:3

"color: blanchedalmond">{{ action.year }}年


"color: blanchedalmond">{{ action.month }}月


"color: blanchedalmond">{{ action.day }}日


"color: blanchedalmond">{{ action.hour }}时


"color: blanchedalmond">{{ action.minute }}分


"color: blanchedalmond">{{ action.second }}秒



#得到的结果为:
2021年
7月
15日
10时
19分
46秒

使用locals(),他可以一次性取出所有值

hello {{ l.0 }}


hello {{ l.1 }}


hello {{ l.2 }}


{{ c.name }}


{{ c.sex }}


#得到的结果为:
hello a
hello b
hello c
alex
man

点语法也可以用来引用对象的方法。 例如,每个 Python 字符串都有 upper() 和 isdigit()
方法,你在模板中可以使用同样的句点语法来调用它们:
>>> from django.template import Template, Context
>>> t = Template('{{ var }} -- {{ var.upper }} -- {{ var.isdigit }}')
>>> t.render(Context({'var': 'hello'}))
'hello -- HELLO -- False'
>>> t.render(Context({'var': '123'}))
'123 -- 123 -- True'

变量的过滤器(filter)的使用
语法:{{obj|filter:参数}}

1 add : 给变量加上相应的值

2 addslashes : 给变量中的引号前加上斜线

3 capfirst : 首字母大写

4 cut : 从字符串中移除指定的字符

5 date : 格式化日期字符串

6 default : 如果值是False,就替换成设置的默认值,否则就是用本来的值

7 default_if_none: 如果值是None,就替换成设置的默认值,否则就使用本来的值

实例
1.add(给变量加上相应的值)的使用
#age = age+2

{{ test_0.age|add:2 }}



#name=kangmin

{{ test_0.name|add:'min' }}



2.capfirst(使变量首字母大写)的使用
name的首字母大写

{{ test_0.name|capfirst }}



3.cut(从字符串中移除指定的字符)的使用
删除空格

{{ test_1|cut:" " }}


删除s,会删除字符串中所有的s

{{ test_1|cut:"s" }}



4.date(格式化日期字符串)的使用

{{ test_2|date:"Y-m-d" }}



5.default(如果值是false,就替换成设置的默认值,否则就是用本来的值default)的使用

{{ test_3 | default:"改变False" }}



6.default_if_none(如果值是None,就替换成设置的默认值,否则就使用本来的值 )的使用

{{ test4|default_if_none:"None改为kang" }}