2011-04-02 20 views
0

目前我正在嘗試爲一個請求創建多個視圖。 1點看,我這樣做:Django的嵌套render_to_response總是顯示內容類型

return render_to_response(
    "/index/index.html", 
    {} 
) 

,現在當我嘗試了「左」列添加到index.html的,我需要把它放在不同的看法(因爲我需要應用相同的技術在其他地方也是如此),這就是我該如何做的:

leftCol = direct_to_template(request,settings.viewPath + "/columns/left.html",{}) 
return render_to_response(
    "/index/index.html", 
    { 
    'leftColumn': leftCol, 
    } 

代碼運行良好,但輸出結果並不符合我的預期。該leftCol顯示在開始其輸出的響應頭:

「的Content-Type:text/html的;字符集= UTF-8」

我如何刪除這個頭?我一直在嘗試修改參數中的content_type和mimetype,但它不起作用。

+0

的leftCol用使用direct_to_template,這是選擇render_to_response以及之前。但結果是一樣的。 – kecebongsoft 2011-04-02 12:25:04

+0

閱讀有關呈現內容的文檔:http://docs.djangoproject.com/en/dev/ref/templates/api/#rendering-a-context另一種方法可以是使用模板標記或包含(直接在模板上級別) – Jerzyk 2011-04-02 14:22:30

回答

4

這是因爲direct_to_template()返回一個HttpResponse,而不是一個字符串。您是否考慮過使用模板功能,例如{% include %}模板標籤,還是自己寫模板標籤?

如果您堅持在視圖中預渲染模板,然後將它們組合到您的模板中,請親自渲染模板,而不是使用direct_to_template()。例如

from django.template.loader import get_template 
from django.template import RequestContext 

def someview(request): 
    leftCol = get_template(settings.viewPath + "/columns/left.html").render(RequestContext(request) 
    render_to_response("/index/index.html", {'leftColumn': leftCol}) 
+0

是的,模板標籤 - 特別是包含標籤 - 是更好的選擇。 – 2011-04-02 14:50:45

4

使用render_to_stringhttp://docs.djangoproject.com/en/dev/ref/templates/api/#the-render-to-string-shortcut)渲染模板後得到一個字符串返回。或者,您可以使用{% include %}將模板包含在與當前模板相同的上下文中(但仍然是手動模式)。更好的辦法是使用{% extends 'base.html' %}繼承基礎模板,該基礎模板只包含通用模板功能,您可以使用{% block %}根據自己的意願覆蓋該模板功能,並且可以省略重複的模板內容,如左欄。

+0

增加投票。這正是我需要將模板標記呈現給默認處理的404頁面所需的。真棒。 – mkoistinen 2011-11-15 22:28:19

0

'render_to_response'函數返回一個HttpResponse對象。您可以返回其內容屬性來僅訪問要呈現的輸出,而不是返回對象本身。

response = render_to_response(
    "/index/index.html", 
    { 
    'leftColumn': leftCol, 
    } 
return response.content