2009-12-22 77 views
0

我需要使用render_to_response返回的html转义。 我无法找到任何合适的文档。有人可以指向某个方向吗?如何修改django中的HttpResponse对象?

代码:

return render_to_response(template_name, {return render_to_response(template_name, { 
      'form': form, 
      redirect_field_name: redirect_to, 
      'site': current_site, 
      'site_name': current_site.name, 
     }, context_instance=RequestContext(request)) 

在这里,我需要进行转义响应HTML文本。 我的方式我知道是在读取字符串中的模板文件,并用re.escape()转义并渲染它。 最新更简单的方法是什么?

回答

2

字符串从视图传递到模板通过render_to_response被默认转义。

请参见:http://docs.djangoproject.com/en/dev/topics/templates/#id2

默认情况下在Django,每个模板自动转义每一个变量标签的输出。具体来说,这五个字符转义:

< is converted to &lt; 
> is converted to &gt; 
' (single quote) is converted to &#39; 
" (double quote) is converted to &quot; 
& is converted to &amp; 

我们再次强调的是,这种行为是默认。

2

这听起来像是您希望整个响应被转义 - 这是真的吗?这似乎有点奇怪,但你当然可以做到。

import django.utils.html as html 
string = render_to_string(<all of the args to render_to_response>) 
escaped_string = html.escape(string) 
return HttpResponse(escaped_string) 

我不太清楚是什么人/浏览器上,另一端会这个问题,但它听起来像你问什么。