這篇文章主要介紹了Django框架中render_to_response()函數的使用方法,注意范例中該方法的參數的使用,需要的朋友可以參考下
通常的情況是,我們一般會載入一個模板文件,然后用 Context渲染它,最后返回這個處理好的HttpResponse對象給用戶。 我們已經優化了方案,使用 get_template() 方法代替繁雜的用代碼來處理模板及其路徑的工作。 但這仍然需要一定量的時間來敲出這些簡化的代碼。 這是一個普遍存在的重復苦力勞動。Django為此提供了一個捷徑,讓你一次性地載入某個模板文件,渲染它,然后將此作為 HttpResponse返回。
該捷徑就是位于 django.shortcuts 模塊中名為 render_to_response() 的函數。大多數情況下,你會使用``/ ``````對象,除非你的老板以代碼行數來衡量你的工作。
- System Message: WARNING/2 (<string>, line 1736); backlink
- Inline literal start-string without end-string.
- System Message: WARNING/2 (<string>, line 1736); backlink
- Inline literal start-string without end-string.
- System Message: WARNING/2 (<string>, line 1736); backlink
- Inline literal start-string without end-string.
下面就是使用 render_to_response() 重新編寫過的 current_datetime 范例。
- from django.shortcuts import render_to_response
- import datetime
- def current_datetime(request):
- now = datetime.datetime.now()
- return render_to_response('current_datetime.html', {'current_date': now})
大變樣了! 讓我們逐句看看代碼發生的變化:
我們不再需要導入 get_template 、 Template 、 Context 和 HttpResponse 。相反,我們導入 django.shortcuts.render_to_response 。 import datetime 繼續保留.
在 current_datetime 函數中,我們仍然進行 now 計算,但模板加載、上下文創建、模板解析和 HttpResponse 創建工作均在對 render_to_response() 的調用中完成了。 由于 render_to_response() 返回 HttpResponse 對象,因此我們僅需在視圖中 return 該值。
render_to_response() 的第一個參數必須是要使用的模板名稱。 如果要給定第二個參數,那么該參數必須是為該模板創建 Context 時所使用的字典。 如果不提供第二個參數, render_to_response() 使用一個空字典。
新聞熱點
疑難解答