本文實(shí)例講述了Python Django框架模板渲染功能。分享給大家供大家參考,具體如下:
項(xiàng)目名/settings.py(項(xiàng)目配置,配置模板文件的路徑):
import os# 項(xiàng)目目錄的絕對(duì)路徑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文件夾 需要手動(dòng)創(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 HttpResponsefrom 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(視圖,使用模板的簡(jiǎn)單寫法,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對(duì)模板的使用步驟進(jìn)行了封裝。 第三個(gè)參數(shù)可以省略不寫
templates/應(yīng)用名/index.html(模板文件,需要手動(dòng)創(chuàng)建,settings.py中配置模板路徑):
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>模板文件</title></head><body><h1>這是一個(gè)模板文件</h1>使用模板變量:<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是空列表,就會(huì)顯示該內(nèi)容。 {% endfor %}
模板文件的加載(查找)順序:
希望本文所述對(duì)大家基于Django框架的Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選