Django day06 模版層(一) 變數和深度查詢
阿新 • • 發佈:2018-11-09
一.模版語法之變數:
1 - {{ 變數 }} ******重要*******{#這個相當於print了該變數#}
def index(request): name = 'prince' #字串 age = 20 #數字型別 ll = [233, 290, 'bp', 'dsb'] #列表 tu = (1, 2, 3) #元組 dic = {'name': 'prince', 'age': 20, 'll': [1, 2, 3, 4]}
# 在模板上相當於執行了test函式,列印了return的結果def test(): print('prince') return 'bpcsmdj' # 類和物件 class Person(): # Person 人 def __init__(self, name, age): self.name = name self.age = age def get_name(self): return self.name # 物件 @classmethoddef cls_test(cls): return 'cls' @classmethod def stetic_test(cls): return 'stetic' # 類 prince = Person('prince', 20) bastard = Person('bastard', 1000) Person_list = [prince, bastard] Person_dic = {'prince': prince, 'bastard': bastard} 在index.html檔案中: {#模板語言註釋:前端看不到{##} {#這個相當於print了該變數#} <h1>模版語言之變數</h1> <p>字串:{{ name }}</p> <p>數字型別:{{ age }}</p> <p>列表:{{ ll }}</p> <p>元組:{{ tu }}</p> <p>字典:{{ dic }}</p> {#只寫函式名:相當於函式名(),執行該函式#} <p>函式:{{ test }}</p> <p>列表套物件:{{ Person_list }}</p> <p>字典套物件:{{ Person_dic }}</p> # return render(request, 'index.html', {'name': name}) # locals 會把index檢視函式內(***全域性變數是不可能的***)所有的變數當做引數傳到index.html模版裡面,開啟連線時都能取到 return render(request, 'index.html', locals())
2 - 深度查詢:統一都用句點符 " . "
在index.html檔案中: <h1>深度查詢</h1> {#深度查詢:統一都用句點符 " . " #} <p>列表第0和第3個值:{{ ll.0 }} 和 {{ ll.3 }}</p> <p>字典取值:{{ dic.name }} 和 {{ dic.age }}</p> <p>物件取資料屬性:{{ prince.name }}</p> <p>物件取繫結給物件的函式屬性:{{ prince.get_name }}</p> {#取得物件都是它們的 return 返回值#} <p>物件取繫結給類的函式屬性:{{ prince.cls_test }}</p> <p>物件取靜態方法:{{ prince.static_test }}</p> <p>從物件列表中取出prince的年齡:{{ Person_list.0.age }}</p> {#拓展:字串也可以用句點符來呼叫,但是不能調有引數的方法#} <p>字串的方法:{{ name.upper }}</p>