怎么在Python中使用Django框架實現(xiàn)一個模板渲染功能?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。
項目名/settings.py(項目配置,配置模板文件的路徑):
import os # 項目目錄的絕對路徑 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], # 設(shè)置模板文件目錄(templates文件夾 需要手動創(chuàng)建) 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ]
應(yīng)用名/views.py(視圖,使用模板的詳細(xì)步驟):
from django.http import HttpResponse from django.template import loader,RequestContext # 定義視圖函數(shù) (必須傳遞HttpRequest參數(shù)) (需要在urls.py中配置路由) def index(request): # 1.獲取模板 template = loader.get_template('應(yīng)用名/index.html') # 需要在settings.py中配置模板目錄 # 2.定義上下文 (分配的模板變量) context = RequestContext(request,{'title':'圖書列表','list':range(10)}) # 3.渲染模板并返回 (生成html內(nèi)容) return HttpResponse(template.render(context))
應(yīng)用名/views.py(視圖,使用模板的簡單寫法,render):
from django.shortcuts import render # 導(dǎo)入render # 視圖函數(shù) def index(request): context = {'title':'圖書列表','list':list(range(1,10))} # 字典,分配給模板的變量 return render(request,'應(yīng)用名/index.html',context) # render對模板的使用步驟進(jìn)行了封裝。 第三個參數(shù)可以省略不寫
templates/應(yīng)用名/index.html(模板文件,需要手動創(chuàng)建,settings.py中配置模板路徑):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>模板文件</title> </head> <body> <h2>這是一個模板文件</h2> 使用模板變量:<br/> {{ title }}<br/> 使用列表:<br/> {{ list }}<br/> for循環(huán):<br/> <ul> {% for i in list %} <li>{{ i }}</li> {% endfor %} </ul> </body> </html>
模板變量使用:{{ 模板變量名 }}
模板代碼段:{% 代碼段 %}
for循環(huán):
{% for i in list %} {% empty %} 如果遍歷的list是空列表,就會顯示該內(nèi)容。 {% endfor %}
模板文件的加載(查找)順序:
看完上述內(nèi)容,你們掌握怎么在Python中使用Django框架實現(xiàn)一個模板渲染功能的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
分享標(biāo)題:怎么在Python中使用Django框架實現(xiàn)一個模板渲染功能-創(chuàng)新互聯(lián)
網(wǎng)址分享:http://jinyejixie.com/article12/dphegc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供服務(wù)器托管、動態(tài)網(wǎng)站、網(wǎng)站改版、網(wǎng)站排名、電子商務(wù)、靜態(tài)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)