Django TemplateResponse与渲染 [英] Django TemplateResponse vs render
问题描述
return TemplateResponse(request, self.template_name, context=context)
和
return render(request, self.template_name, context=context)
在任何情况下,为什么我应该使用其中一个而不是另一个?
Is there any scenario why I should use one of them and not the other?
推荐答案
TemplateResponse
将模板的渲染延迟到视图完成之后.这样,任何模板响应中间件都可以在响应上运行,并且可能会在渲染模板之前更改模板或上下文数据.模板响应中间件运行之后,将渲染模板,并在渲染的内容上运行普通响应中间件,然后将响应返回给客户端.
A TemplateResponse
delays the rendering of the template until after the view is finished. This allows any template response middleware to run on the response, and potentially alter the template or the context data before the template is rendered. After the template response middleware has run, the template is rendered, and the normal response middleware is run on the rendered content before the response is returned to the client.
render()
快捷方式立即呈现模板,并返回 HttpResponse
.
The render()
shortcut immediately renders the template and returns a HttpResponse
.
这篇关于Django TemplateResponse与渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!