本文實例講述了Python Django框架模板渲染功能。分享給大家供大家參考,具體如下:
項目名/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')], # 設置模板文件目錄(templates文件夾 需要手動創建) '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', ], }, },]
應用名/views.py(視圖,使用模板的詳細步驟):
from django.http import HttpResponsefrom django.template import loader,RequestContext# 定義視圖函數 (必須傳遞HttpRequest參數) (需要在urls.py中配置路由)def index(request): # 1.獲取模板 template = loader.get_template('應用名/index.html') # 需要在settings.py中配置模板目錄 # 2.定義上下文 (分配的模板變量) context = RequestContext(request,{'title':'圖書列表','list':range(10)}) # 3.渲染模板并返回 (生成html內容) return HttpResponse(template.render(context))
應用名/views.py(視圖,使用模板的簡單寫法,render):
from django.shortcuts import render # 導入render# 視圖函數def index(request): context = {'title':'圖書列表','list':list(range(1,10))} # 字典,分配給模板的變量 return render(request,'應用名/index.html',context) # render對模板的使用步驟進行了封裝。 第三個參數可以省略不寫
templates/應用名/index.html(模板文件,需要手動創建,settings.py中配置模板路徑):
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>模板文件</title></head><body><h1>這是一個模板文件</h1>使用模板變量:<br/>{{ title }}<br/>使用列表:<br/>{{ list }}<br/>for循環:<br/><ul> {% for i in list %} <li>{{ i }}</li> {% endfor %}</ul></body></html>
模板變量使用:{{ 模板變量名 }}
模板代碼段:{% 代碼段 %}
for循環:
{% for i in list %} {% empty %} 如果遍歷的list是空列表,就會顯示該內容。 {% endfor %}
模板文件的加載(查找)順序:
希望本文所述對大家基于Django框架的Python程序設計有所幫助。
新聞熱點
疑難解答