我正在经历一些我认为有些奇怪的行为。具体来说,如果我有这样的字符串:
1984: Curriculum Unit
by Donald R. Hogue, Center for Learning, George Orwell
"A center for learning publication"--Cover.
被 Django 模板系统自动转义后,结果如下:
1984: Curriculum Unit
by Donald R. Hogue, Center for Learning, George Orwell
"A center for learning publication"--Cover.
问题似乎是应该变成 "
的“(引号)被转义两次,导致 &"
。这会导致格式看起来很奇怪。我使用的是 Django 1.0.2,所以它应该是最新的,(尽管我应该注意我正在使用 Ubuntu 9.04 包含的软件包 python-django),但这种行为似乎与预期行为相反。
我查看了 django.utils.html.py,其中包含实际功能:
def escape(html):
"""Returns the given HTML with ampersands, quotes and carets encoded."""
return mark_safe(force_unicode(html).replace('&','&').replace('<','<').replace('>', '>').replace('"', '"').replace("'",'''))
转义=allow_lazy(转义,unicode)
block 引用>无论如何,看起来应该在其他任何事情之前转义 & ,这样就可以了。所以我怀疑它被调用了两次。有什么想法吗?
谢谢。
更新:我怀疑它可能与 Ubuntu 的 Django 有关,它列为“1.0.2-1”,所以我安装了“1.0.2-final”并遇到了问题同样的问题。
最佳答案
你不应该考虑在 1.0 中转义。如果您有模板
<html>
<body>
& == & in HTML
</body>
</html>
在打印之前,它应该将 &
编码为 &
。
如果你有一个变量
<html>
<body>
{{ msg }}
</body>
</html>
和
def view(request) :
msg = "& == & in HTML"
如果应该以同样的方式打印。
只有当您需要粘贴原始 html 时,您才需要自己进行编码。喜欢:
def view(request) :
msg = '<img src="http://example.com/pretty.jpg" />This picture is very pretty'
并在您的模板中
<html>
<body>
{{ msg|safe }}
</body>
</html>
关于python - Django 双转义引号等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1157725/