django基礎--模板 (python的模板:HTML程式碼+模板語法)
模板語法--變數
在 Django 模板中遍歷複雜資料結構的關鍵是句點字元, 語法: {{var_name}}
想要獲得下一級資料, 比如列表l
第一個資料, 使用.
來獲取資料, {{ l.0 }}
, 這種語法也叫深度查詢
測試資料
views.py
from django.shortcuts import render,HttpResponse from django.urls import reverse # Create your views here. def index(request): name='wang' i=10 l=[111,222,333] info={ 'name':'wtp', 'age':30 } b=True class Person(object): def __init__(self,name,age): self.name=name self.age=age ross=Person('ross',35) joey=Person('joey',36) person_list=[ross,joey] return render(request,'index.html',locals())
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> </head> <body> <p>name: {{ name }}</p> <p>i: {{ i }}</p> <p>l: {{ l }}</p> <p>info: {{ info }}</p> <p>b: {{ b }}</p> <p>ross: {{ ross }}</p> <p>joey: {{ joey }}</p> <p>person_list: {{ person_list }}</p> <h4>{{s}}</h4> <h4>列表:{{ l.0 }}</h4> <h4>列表:{{ l.2 }}</h4> <h4>字典:{{ dic.name }}</h4> <h4>日期:{{ date.year }}</h4> <h4>類物件列表:{{ person_list.0.name }}</h4> </body> </html>
模板語法--過濾器
語法: {{obj|filter__name:param}}
過濾器date舉例
views.py
from django.shortcuts import render,HttpResponse
from django.urls import reverse
# Create your views here.
def index(request):
import datetime
now=datetime.datetime.now()
return render(request,'index.html',locals())
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> </head> <body> <h4>now:{{ now|date:"Y-m-d" }}</h4> </body> </html>
default
如果一個變數是false或者為空,使用給定的預設值。否則,使用變數的值。例如:
{{ value|default:``"nothing"
}}
length
返回值的長度。它對字串和列表都起作用。例如:
{{ value|length }}
如果 value 是 ['a', 'b', 'c', 'd'],那麼輸出是 4。
filesizeformat
將值格式化為一個 “人類可讀的” 檔案尺寸 (例如 '13 KB'
, '4.1 MB'
, '102 bytes'
, 等等)。例如:
{{ value|filesizeformat }}
如果 value
是 123456789,輸出將會是 117.7 MB
slice
如果 value="hello world"
{{ value|
slice
:``"2:-1"}}
truncatechars
如果字串字元多於指定的字元數量,那麼會被截斷。截斷的字串將以可翻譯的省略號序列(“...”)結尾。
引數:要截斷的字元數
{{ value|truncatechars:``9
}}
safe
Django的模板中會對HTML標籤和JS等語法標籤進行自動轉義,原因顯而易見,這樣是為了安全。
為了在Django中關閉HTML的自動轉義有兩種方式,如果是一個單獨的變數我們可以通過過濾器“|safe”的方式告訴Django這段程式碼是安全的不必轉義。比如:
views.py
def index(request):
context={
'value':"<script>alert('hello world')</script>"
}
return render(request,'index.html',locals())
- 沒有使用safe過濾器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body>
{{ context.value }}
</body>
</html>
- 使用safe過濾器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body>
{{ context.value|safe }}
</body>
</html>
模板語法--標籤
標籤看起來像是這樣的: {% tag %}
。標籤比變數更加複雜:一些在輸出中建立文字,一些通過迴圈或邏輯來控制流程,一些載入其後的變數將使用到的額外資訊到模版中。一些標籤需要開始和結束標籤 (例如{% tag %} ...
標籤 內容 ... {% endtag %})。
for標籤
- 遍歷每一個元素
{% for person in person_list %}
<p>{{ person.name }}</p>
{% endfor %}
可以利用{% for obj in list reversed %}
反向完成迴圈。
- 遍歷一個字典:
{% for key,val in dic.items %}
<p>{{ key }}:{{ val }}</p>
{% endfor %}
注:迴圈序號可以通過{{forloop}}顯示
forloop.counter The current iteration of the loop (1-indexed)
forloop.counter0 The current iteration of the loop (0-indexed)
forloop.revcounter The number of iterations from the end of the loop (1-indexed)
forloop.revcounter0 The number of iterations from the end of the loop (0-indexed)
forloop.first True if this is the first time through the loop
forloop.last True if this is the last time through the loop
for ... empty
for
標籤帶有一個可選的{% empty %}
從句,以便在給出的組是空的或者沒有被找到時,可以有所操作。
{% for person in person_list %}
<p>{{ person.name }}</p>
{% empty %}
<p>sorry,no person here</p>
{% endfor %}
if標籤
{% if %}
會對一個變數求值,如果它的值是“True”(存在、不為空、且不是boolean型別的false值),對應的內容塊會輸出
{% if num > 100 or num < 0 %}
<p>無效</p>
{% elif num > 80 and num < 100 %}
<p>優秀</p>
{% else %}
<p>湊活吧</p>
{% endif %}
with
使用一個簡單地名字快取一個複雜的變數,當你需要使用一個“昂貴的”方法(比如訪問資料庫)很多次的時候是非常有用的
例如:
{% with total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
{% endwith %}
csrf_token
這個標籤用於跨站請求偽造保護
{% csrf_token %}