1.模板路徑的查找
- 查找順序
- 首先會在根目錄下的templates文件夾下面查找
- 之后會在已注冊的app中的templates文件夾下面查找
- 只要找到一個符合的模板,就返回
- 兩種方案
- 項目部署
- app復(fù)用
2.靜態(tài)頁面烟馅,動態(tài)頁面
- 靜態(tài)頁面:無法變化,
- 動態(tài)頁面:根據(jù)交互的不同會進行變化
3.渲染機制
- 可以將模板變量渲染進入頁面
class Index(View):
def get(self, request):
now = datetime.now()
return render(request, 'index/home.html', context={
'now': now
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>主頁</title>
</head>
<body>
<h1>我是主頁</h1>
<h4>當(dāng)前時間是:{{ now }}</h4>
</body>
</html>
4.模板變量
- 語法
- 語法: {{ 變量名 }}
- 命名由字母和數(shù)字以及下劃線組成欺缘,不能有空格和標(biāo)點符號
- 可以使用字典、模型、方法、函數(shù)傍念、列表
- 不要和python或django關(guān)鍵字重名
- 變量和查找
- 變量的解析規(guī)則
- 計算變量,將其替換為結(jié)果
- 遇到點(.)的時候葛闷,按一下順序查找:
- 字典鍵值查找
- 屬性或方法查找
- 數(shù)字索引查找
- 如果結(jié)果是可調(diào)用的,則調(diào)用它時不帶參數(shù)双藕。調(diào)用的結(jié)果成為模板的值
- 所謂的結(jié)果是可調(diào)用的淑趾,說明變量是不帶參數(shù)個函數(shù),或是個方法
- 渲染失敗返回: ''
class Fruits:
def __init__(self, name, color):
self.name = name
self.color = color
def food(self):
return '水果也是食物哦'
class Index(View):
def get(self, request):
now = datetime.now()
list1 = [1,2,3]
dict1 = {'name': '劉威', 'age': 18}
dict2 = {'name': '劉威', 'age': 18, 'items':'abc'}
def func():
return '我是一個無參數(shù)的可調(diào)用函數(shù)'
fruit = Fruits('apple', 'red')
return render(request, 'index/home.html', context={
'now': now,
'list1':list1,
'dict1': dict1,
'dict2': dict2,
'func':func,
'fruit':fruit,
})
<body>
<h4>變量調(diào)用:{{ now }}</h4>
<h4>列表調(diào)用:{{ list1}}</h4>
<h4>列表值調(diào)用:{{ list1.2}}</h4>
<h4>字典調(diào)用:{{ dict1 }}</h4>
<h4>字典key調(diào)用:{{ dict1.name }}</h4>
<h4>字典方法調(diào)用:{{ dict2.items }}</h4>
<h4>函數(shù)調(diào)用:{{ func }}</h4>
<h4>類對象調(diào)用:{{ fruit }}</h4>
<h4>類對象屬性調(diào)用:{{ fruit.name }}</h4>
<h4>類對象方法調(diào)用:{{ fruit.food }}</h4>
</body>
模板變量.png
5.模板過濾器 filter
-
作用:對變量進行過濾忧陪。在真正渲染出來之前扣泊,過濾器會根據(jù)功能處理好變量,然后得出結(jié)果后再替換掉原來的變量展示出來
- 語法:{{fruits|lower}}
-
鏈?zhǔn)秸{(diào)用:比如實現(xiàn)一個功能嘶摊,先把所有字符變成小寫延蟹,把第一個字符轉(zhuǎn)換成大寫
- 語法:{{fruits|lower|capfirst}}
-
使用參數(shù):過濾器可以使用參數(shù),在過濾器名稱后面使用冒號”:”再加上參數(shù)叶堆,比如要把一個字符串中所有的空格去掉阱飘,則可以使用cut過濾器
- 語法如下: {{fruits|cut:" "}}
- 注意:使用參數(shù)的時候,冒號和參數(shù)之間不能有任何空格,一定要緊挨著
-
常用模板過濾器
- add 將參數(shù)與值相加 首先嘗試轉(zhuǎn)換成整數(shù)相加沥匈,失敗蔗喂,則嘗試字符串,列表相加等高帖。{{ value|add:"2" }}
- capfirst 首字母大寫缰儿,如果第一個字母不是字母則不起作用。{{ value|capfirst }}
- date 日期格式化 {{ value|date:"D d M Y" }}
- time 時間格式化 {{ value|time:"H:i" }} 格式化格式見官方文檔:https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#date
- default 如果變量解析失敗散址,使用給定的默認(rèn)值乖阵。{{ value|default:"nothing" }}(注意如果value是''空字符串,輸出將會是'nothing')
- first 返回列表的第一個元素 {{ value|first }}
- last 返回列表的最有一個元素 {{ value|last }}
- slice 返回一個列表的切片 {{ some_list|slice:":2" }}预麸,前閉后開
- join 連接字符串列表 與str.join(list)一樣 {{ value|join:" // " }}
- floatformat 浮點數(shù)格式化 不指定小數(shù)位參數(shù)瞪浸,默認(rèn)保留一個為小數(shù)
- length 返回字符串或列表的長度
- length_is 判斷字符串或列表長度是否指定的值,相等返回True {{ value|length_is:"4" }}
- lower 字符串中的字母都變小寫{{ value|lower }}
- upper 字符串中的字母都變大寫{{ value|upper }}
- safe 關(guān)閉變量的自動轉(zhuǎn)義师崎,使html標(biāo)簽生效{{ value|safe }}
- title 標(biāo)題化默终,首字母大寫 {{ value|title }}
- truncatechars 根據(jù)后面給的參數(shù),截斷字符犁罩,如果超過了用...表示
- truncatewords 同truncatechars齐蔽,不過這個一個以單詞為單位,進行截斷
以上兩個針對html床估,會截斷標(biāo)簽中的字符含滴,而不會截斷標(biāo)簽 - striptags 去掉所有的html標(biāo)簽
xss 跨域腳本攻擊
class Index(View):
def get(self, request):
# 用js寫個死循環(huán)alert(1), 在渲染到前端,有興趣的可以試試
js= '<script>alert(1)</script>'
return render(request, 'index/home.html', context={
'js':js
})
<body>
<p>{{ js|safe }}</p>
</body>
6.靜態(tài)文件(static:css js image)
- 路徑配置
# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,'static')]
- 靜態(tài)文件的引入
{# index.html #}
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>主頁</title>
<link rel="stylesheet" href="{% static 'css/index/index.css' %}">
</head>
<body>
<p>我是紅色</p>
</body>
</html>
/* index.css */
p{
color: red;
}
- 訪問
# index.views.py
from django.views import View
from django.shortcuts import render,
class Index(View):
def get(self, request):
return render(request, 'index/home.html')
# index/urls.py
from django.views import View
from django.shortcuts import render,
class Index(View):
def get(self, request):
return render(request, 'index/home.html')
7.Bootstrap套用舉例
image.png
image.png
image.png
image.png
image.png
再獲取網(wǎng)頁源代碼丐巫,以及相應(yīng)css文件谈况,導(dǎo)入到我們的項目中,進行代碼設(shè)計
image.png
{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3個meta標(biāo)簽*必須*放在最前面递胧,任何其他內(nèi)容都*必須*跟隨其后碑韵! -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Signin Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link rel="stylesheet">
<!-- Custom styles for this template -->
<link href="{% static 'css/login/login.css' %}" rel="stylesheet">
</head>
<body>
<div class="container">
<form class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
</body>
</html>
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #eee;
}
.form-signin {
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
margin-bottom: 10px;
}
.form-signin .checkbox {
font-weight: normal;
}
.form-signin .form-control {
position: relative;
height: auto;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 10px;
font-size: 16px;
}
.form-signin .form-control:focus {
z-index: 2;
}
.form-signin input[type="email"] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-signin input[type="password"] {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
class Login(View):
def get(self, request):
return render(request, 'login/login.html')
urlpatterns = [
path('login/', views.Login.as_view(), name='login'),
]