一.两种模板方法
-
变量相关 :
{ { }}
-
逻辑相关 :
{% %}
二.注释
- 注释是代码之母 :
{# #}
三.模板语法之传值
1.Python中基本数据类型传值
def test_func(request):
s = "Hello 派大星!"
i = 1314520
f = 1.75
l = [1,2,3,4,5]
d = {
"name":"shawn","age":23}
t = (2,3,4,5,5)
se = {
3,4,5,'rr'}
b = True
# 传值方式一 : 使用字典的格式一个个传
return render(request,'test.html',{
'strs':s,'ints':i,'lists':l,...})
# 传值方式二 : 使用 locals()将当前名称空间所有的变量名全部传递微页面
return render(request,'test.html',locals())
- test.html 文件
<h1>{
{ s }}</h1>
<h1>{
{ i }}</h1>
<h1>{
{ f }}</h1>
<h1>{
{ l }}</h1>
<h1>{
{ d }}</h1>
<h1>{
{ t }}</h1>
<h1>{
{ se }}</h1>
<h1>{
{ b }}</h1>
2.函数与类的传递
def test_func(request):
def aa():
print("aa--->")
return 'I am aa'
class Bar(object):
def cc(self):
print("Bar-->cc")
B1 = Bar()
return render(request, 'test.html', locals())
- 模板层
<h1>{
{ aa }}</h1>
<h1>{
{ Bar }}</h1>
<h1>{
{ B1 }}</h1>
3.函数名与类名注意点
- 传递函数名与类名都会自动加括号调用
- 传入函数名得到的结果是函数的返回值
- 模板语法不支持额外的传参,也就是函数无法传参
4.传值方式优缺点 :
- 传值方式一 : 传值精确, 不会造成资源浪费
- 传值方式二 : 传值简单, 可能造成一定的资源浪费
四.模板语法之获取值
-
django模板语法取值只能采用句点符(.),也就是点
-
可以根据索引以及键取值,支持多个很多个点…
# views.py
def test_func(request):
ll = [1,2,{
"name":"shawn","age":23,"hobby":["read","study"]}]
return render(request,"test.html",{
"ll":ll})
# 想要取出爱好read
# test.html
<h1>{
{
ll.2.hobby.0 }}</h1>
五.模板语法之过滤器Filter
1.过滤器说明
- 类似于Python的内置方法
- 将竖杠左侧的数据当做第一个参数传给右边的过滤器
- 语法 :
{ { [数据]|过滤器:可选参数 }}
- 注意 : 竖杠左右两边没有空格
- 过滤器参数包含空格的话需要使用引号包裹
- 过滤器最多只能有两个参数
2.常用过滤器使用
- django中大约60中过滤器,下面只介绍常用过滤器
# views.py
def test_func(request):
s = "Hello 派大星!"
i = 1314520
f = 1.75
l = [1,2,3,4,5]
d = {
"name":"shawn","age":23}
t = (2,3,4,5,5)
se = {
3,4,5,'rr'}
b = True
w = 'aa bb cc dd ee ff'
return render(request,'test.html',locals())
<!-- test.html-->
<p>统计长度:{
{ s|length }}</p>
<!-- add数字相加,字符拼接-->
<p>加法运算:{
{ i|add:1000 }}</p>
<p>字符串拼接:{
{ s|add:'Hello 海绵宝宝' }}