本文實例講述了Django框架模板文件使用及模板文件加載順序。分享給大家供大家參考,具體如下:
模板功能
產生html,控制頁面上產生的內容。模板文件不僅僅是一個html文件。
模板文件包含兩部分內容:
1.靜態文件:css,js,html
2.動態內容:用于動態的去產生一些網頁內容,通過模板語言產生
模板文件的使用
通常是在視圖函數中使用模板產生html內容返回給客戶端
a,加載模板文件 loader.get_template
獲取模板文件的內容,產生一個模板對象
b,定義模板上下文 RequestContext
給模板文件傳遞數據
c,模板文件渲染產生的html頁面內容 render
用傳遞的數據替換相應的變量,產生一個替換后的表中html內容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
from django.shortcuts import render from django.template import loader,RequestContext from django.http import HttpResponse # Create your views here. def my_render(request,template_path,context = {}): # 1.加載模板文件,獲取一個模板對象 temp = loader.get_template(template_path) # 2.定義模板上下文,給模板傳遞數據 context = RequestContext(request, context) # 3.模板渲染,產生一個替換后的html內容 res_html = temp.render(context) # 4.返回應答 return HttpResponse(res_html) # /index def index(request): # return my_render(request,'booktest/index.html') 這是自己封裝的render # 其實Django已經封裝好了,可以直接使用 return render(request, 'booktest/index.html' ) |
模板文件的加載順序
1.首先去配置的模板目錄下找模板文件
2.去INSTALL_APPS下面的每個應用去找模板文件,前提是應用中必須有templates文件夾
希望本文所述對大家基于Django框架的Python程序設計有所幫助。
原文鏈接:https://blog.csdn.net/qq_34788903/article/details/87905687