目前我参考了我公司的 django 1.9 版本中创建的一些旧项目,我发现他们已经多次使用 render_to_string 函数,现在我正在使用渲染函数,但我从未使用过 render_to_string。
render_to_string 函数的示例代码如下。
return HttpResponse(render_to_string('sales/sale.html', {'sale_id' : sale_id, `unique_number`:uni_id}, RequestContext(request)))
Run Code Online (Sandbox Code Playgroud)
我试图在网上搜索找到答案,但找不到任何完美的答案。
这两个功能及其行为方式之间有什么区别?
什么时候决定哪个功能最适合在项目中使用?
谢谢。
我们可以查看[GitHub]的源代码render:
Run Code Online (Sandbox Code Playgroud)def render(request, template_name, context=None, content_type=None, status=None, using=None): """ Return a HttpResponse whose content is filled with the result of calling django.template.loader.render_to_string() with the passed arguments. """ content = loader.render_to_string(template_name, context, request, using=using) return HttpResponse(content, content_type, status)
本质上render,因此render_to_string(..)使用template_name、context、request和using作为参数进行调用,然后HttpResponse使用该结果以及可选的 acontent_type和构造 a status。因此,这是将两者结合起来的捷径。