Django's nested render_to_response always show content-type
Currently I am trying to create multiple view for one request. For 1 view, I am doing this:
return render_to_r开发者_高级运维esponse(
"/index/index.html",
{}
)
And now when I try to add a "left" column to index.html, I need to put it on different view (because I need to apply the same technique on other place as well), this is how I do it:
leftCol = direct_to_template(request,settings.viewPath + "/columns/left.html",{})
return render_to_response(
"/index/index.html",
{
'leftColumn': leftCol,
}
The code works well, but the output is not what I expected. The leftCol shows the response header at the beginning of it's output:
"Content-Type: text/html; charset=utf-8"
How do I remove this header? I've been trying to modify the content_type and mimetype in the parameter but it didn't work.
That's because direct_to_template()
returns a HttpResponse
, not a string. Have you considered using templating functionality, e.g. the {% include %}
template tag, or writing a template tag of your own?
If you insist on pre-rendering templates in your view and then combining them in your template, render the template yourself, rather than using direct_to_template()
. e.g.
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})
Use render_to_string
(http://docs.djangoproject.com/en/dev/ref/templates/api/#the-render-to-string-shortcut) to get a string back after rendering a template. Alternatively, you can use an {% include %}
to include a template in the same context as the current template (but this is still manual). Even better would be to have a base template that you inherit using {% extends 'base.html' %}
which will just include common template functionality that you can override at your will using {% block %}
and enables you to leave out duplicated template content like a left column.
The 'render_to_response' function returns an HttpResponse object. Instead of returning the object itself, you can return its content attribute to access only the output you want to render.
i.e.
response = render_to_response(
"/index/index.html",
{
'leftColumn': leftCol,
}
return response.content
精彩评论