您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“Python中Django模板系統(tǒng)的示例分析”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學習一下“Python中Django模板系統(tǒng)的示例分析”這篇文章吧。
在django項目下創(chuàng)建templats文件來存放html文件
為了減少模板加載調(diào)用過程及模板本身的冗余代碼,Django 提供了一種使用方便且功能強大的 API ,當使用模板加載API時,需要將模板路徑告訴框架,在項目settings.py
中設(shè)置模板路徑,如圖:
settings.py
中的BASE_DIR
為項目路徑。
在TEMPLATES
中的BIRS
來設(shè)置模板路徑
templates
下編寫index.html
寫入如下代碼:
!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首頁</title> </head> <body> <h2>hello world!</h2> </body> </html>
視圖文件view.py中編寫如下代碼,通過render渲染html文件:
from django.shortcuts import render # 獲取對應模板通過render渲染 def index(request): return render(request, 'index.html')
結(jié)果如下:
Django模板中使用{{ }}來表示變量:
{{ 變量名 }}:變量名由字母數(shù)字和下劃線組成,其值可以是任何數(shù)據(jù)類型
舉例如下:
當模板引擎遇到變量時,會計算該變量,并將其替換為結(jié)果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首頁</title> </head> <body> <h4>{{ content }}</h4> <h4>{{ info }}</h4> </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> <h4>{{ content }}</h4> <!-- 獲取字典中key的值 --> <h4>{{ info.name }}</h4> <!-- 通過索引獲取列表的值 --> <h4>{{li.1}}</h4> <!-- 調(diào)用不帶參數(shù)的方法 --> <h4>{{ fun }}</h4> <!-- 獲取對象屬性 --> <h4>{{ obj.name }}</h4> </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})
首先在項目根目錄下創(chuàng)建存放靜態(tài)文件的目錄,并在settings中設(shè)置路徑,如下:
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中Django模板系統(tǒng)的示例分析”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學習更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。