Python Django模板系統(tǒng)詳解
設置模板路徑
在django項目下創(chuàng)建templats文件來存放html文件
為了減少模板加載調用過程及模板本身的冗余代碼,Django 提供了一種使用方便且功能強大的 API ,當使用模板加載API時,需要將模板路徑告訴框架,在項目settings.py
中設置模板路徑,如圖:
settings.py
中的BASE_DIR
為項目路徑。
在TEMPLATES
中的BIRS
來設置模板路徑
templates
下編寫index.html
寫入如下代碼:
!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首頁</title> </head> <body> <h1>hello world!</h1> </body> </html>
視圖文件view.py中編寫如下代碼,通過render渲染html文件:
from django.shortcuts import render # 獲取對應模板通過render渲染 def index(request): return render(request, 'index.html')
結果如下:
模板變量
Django模板中使用{{ }}來表示變量:
{{ 變量名 }}:變量名由字母數字和下劃線組成,其值可以是任何數據類型
舉例如下:
當模板引擎遇到變量時,會計算該變量,并將其替換為結果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首頁</title> </head> <body> <h3>{{ content }}</h3> <h3>{{ info }}</h3> </body> </html>
view.py
中render
渲染時通過context以字典形式傳遞值:
from django.shortcuts import render def index(request): content = 'hello world' info = {'name': 'test', 'age': 18} return render(request, 'index.html', context={'content': content, 'info': info})
模板中支持以下語法:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首頁</title> </head> <body> <h3>{{ content }}</h3> <!-- 獲取字典中key的值 --> <h3>{{ info.name }}</h3> <!-- 通過索引獲取列表的值 --> <h3>{{li.1}}</h3> <!-- 調用不帶參數的方法 --> <h3>{{ fun }}</h3> <!-- 獲取對象屬性 --> <h3>{{ obj.name }}</h3> </body> </html>
view.py:
from django.shortcuts import render def index(request): content = 'hello world' info = {'name': 'test', 'age': 18} li = [1, 2, 3] class Obj: def __init__(self, name): self.name = name M = Obj('對象屬性:MING') def fun(): return '方法:fun' return render(request, 'index.html', context={'content':content,'info': info,'li': li,'fun': fun,'obj': M})
引用靜態(tài)文件
首先在項目根目錄下創(chuàng)建存放靜態(tài)文件的目錄,并在settings中設置路徑,如下:
STATIC_URL = '/static/'
為靜態(tài)文件引用前綴,當引用文件時代表的是文件根目錄,如下:
static
代表的是statics
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首頁</title> </head> <body> <!-- 圖片 --> <img src="/static/img/123.jpg" alt=""> </body> </html>
view.py:
from django.shortcuts import render def index(request): return render(request, 'index.html')
總結
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關注腳本之家的更多內容!
相關文章
在python中獲取div的文本內容并和想定結果進行對比詳解
今天小編就為大家分享一篇在python中獲取div的文本內容并和想定結果進行對比詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01PyTorch與PyTorch?Geometric的安裝過程
這篇文章主要介紹了PyTorch與PyTorch?Geometric的安裝,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04