DTL語言,即django template language
第一次使用時,需要修改項目的setting.py文件,將其中TEMPLATES中的DIRS修改為os.path.join(BASE_DIR, 'templates'),BASE_DIR在setting.py文件中定義為BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))),表示項目所在的文件夾
使用render時,系統會默認從setting.py文件的TEMPLATES中的DIRS所指的路徑尋找渲染文件
如果DIRS為空,而APP_DIRS為True,系統則會從項目的各個app的templates目錄下去尋找渲染文件,前提是app已經添加到setting.py文件的INSTALLED_APPS中。
templates的查找順序:DIRS、APP_DIRS
#項目的setting.py中templates的最初配置 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] #INSTALLED_APPS的最初配置 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]
template_intro_demo
渲染模板的兩種方式
1.需要導入from django.template.loader import render_to_string,最后HttpResponse返回一個render_to_string的值
例如html=render_to_string('index.html') return HttpResponse(html)
2.直接通過render返回,render返回的第一個參數為request,第二個為要渲染的文件名稱,一般使用這種方式
return render(request,'index.html')
在模板中使用變量,有兩種方法,但在html模板中必須將變量放在{{ 變量 }}中
①將變量存放在字典中,在render中通過context=字典的形式接收變量,然后在模板中直接通過字典的鍵值引用
#視圖函數 from django.shortcuts import render def index(request): con={'username':'ahahhah','age':25,'hobby':'basketball'} #定義變量,變量只能為字典形式 return render(request,'index.html',context=con) #render只能通過context接收變量 #渲染文件 …… <body> {{ username }} #直接使用字典的鍵獲取鍵值,不需要使用context.鍵否則無法獲取到值 {{ age }} {{ hobby }} </body> ……
②變量以任何形式存在,在render中通過{'接收變量的名稱':'變量名稱'}的形式接收變量,然后在模板中通過接收變量的名稱(如果為列表、元組、字典、對象等,需通過下標訪問)引用
#視圖函數 from django.shortcuts import render def index(request): con=['ahahhah',25,'basketball'] #定義變量,可以是數字、字符串、列表、元組、字典、對象等 return render(request,'index.html',{'person':con}) #render通過字典形式接收變量 #渲染文件 …… <body> {{ person.0 }} #以render中的字典的鍵來表示變量,並通過索引下標訪問值 {{ person.1 }} {{ person.2 }} </body> ……
1.在模板中使用視圖函數中的變量,需要將變量放置到{{變量名}}中
2.如果在render中通過字典的形式接收變量並且變量為列表、元組、字典、對象等,那么想要訪問變量的值,需要通過變量.屬性來訪問,不能通過python下標的方式訪問,如訪問列表的第3個元素l.2
3.獲取字典所有的key可使用d.keys,但是如果字典中有一個key的名稱也為keys,那么d.keys就會獲取到keys對應的鍵值,因此不建議在字典中定義key為字典的屬性,例如keys、items、values