render 和 render_to_string 有什么区别?

Moo*_*oon 5 python django

目前我参考了我公司的 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)

我试图在网上搜索找到答案,但找不到任何完美的答案。

这两个功能及其行为方式之间有什么区别?

什么时候决定哪个功能最适合在项目中使用?

谢谢。

Wil*_*sem 4

我们可以查看[GitHub]的源代码render

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)
Run Code Online (Sandbox Code Playgroud)

本质上render,因此render_to_string(..)使用template_namecontextrequestusing作为参数进行调用,然后HttpResponse使用该结果以及可选的 acontent_type和构造 a status。因此,这是将两者结合起来的捷径。

  • @Moon:如果你想生成一个`HttpResponse`,那么通常你使用`render`,当你不打算做出响应时使用`render_to_string`。例如,呈现电子邮件模板、模板的子部分等。 (5认同)