Chinaunix

标题: 求助,关于Django 模板html 自动转义的问题 [打印本页]

作者: avyou    时间: 2013-07-22 19:36
标题: 求助,关于Django 模板html 自动转义的问题
本帖最后由 avyou 于 2013-07-22 19:40 编辑

各位大侠,Django 模板html 自动转义是怎么回事呢?我按官方的手册,
建立一个zhuanyi.html :
  1. hi, {{ name }} <br>

  2. {% autoescape off %}
  3. hi,{{ name }}
  4. {% endautoescape %}
复制代码
在浏览器http://localhost:8000/zy/输出是:
  1. hi, John
  2. hi,John
复制代码
无论是在标签autoescape 内还是标签外,都自动转义了,那如何是不让它转义,原字符输出呢?

我的 urls.py 内容:
  1. from django.conf.urls import *

  2. urlpatterns = patterns('',
  3.     ..
  4.     url(r'^zy/$, zhuanyi),
  5. )
复制代码
vews.py内容:
  1. def zhuanyi(request):
  2.     return render_to_response('zhuanyi.html',{'name':'John'})
复制代码

作者: avyou    时间: 2013-07-22 22:03
本帖最后由 avyou 于 2013-07-22 22:03 编辑

问题解决了,原来是我理解错了。模板字符转义是指传参数进来转义,而不是在原 html上直接转义,如:
转义:
  1. from django import template
  2. H='{% autoescape on %}{{div}}{% endautoescape %}'
  3. c = template.Context({'div':'<html><head></head><title>hello test</title></html>'})
  4. template.Template(H).render(c)
复制代码
输出:
  1. u'&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;title&gt;hello test&lt;/title&gt;&lt;/html&gt;'
复制代码
不转义:
  1. from django import template
  2. H='{% autoescape off %}{{div}}{% endautoescape %}'
  3. c = template.Context({'div':'<html><head></head><title>hello test</title></html>'})
  4. template.Template(H).render(c)
复制代码
输出:
  1. u'<html><head></head><title>hello test</title></html>'
复制代码





欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2