如何在 mako 中正确转义输出(对于 XHTML)?
尽管提供了一种使用过滤器转义输出的好方法,但它们都没有做正确的事情。 获取字符串:
x=u"&\u0092"
过滤器执行以下操作:
x Turns the & into an entity but not the \u0092 (valid XML but not XHTML)
h Exactly the same
u Escapes both, but obviously uses url escaping
entities Only converts named entities, so again only the & is escaped
decode.latin1 The same
HTML 使用标准 UNICODE 联盟字符库,并且未定义(除其他外)65 个字符代码(包括 0 到 31 和 127 到 159)
这些似乎是遗漏的字符。有什么想法吗?
编辑
它似乎验证我是否离线使用该文件。这可能是内容类型问题吗?
Despite offering a nice way to escape output using filters, none of them do the right thing.
Taking the string:
x=u"&\u0092"
The filters do the following:
x Turns the & into an entity but not the \u0092 (valid XML but not XHTML)
h Exactly the same
u Escapes both, but obviously uses url escaping
entities Only converts named entities, so again only the & is escaped
decode.latin1 The same
HTML uses the standard UNICODE Consortium character repertoire, and it leaves undefined (among others) 65 character codes (0 to 31 inclusive and 127 to 159 inclusive)
These seem to be the characters missed. Any ideas?
EDIT
It seems to validate if I use the file offline. Could this be a Content-Type problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无需将 Unicode 字符转换为
&#xxxx;
形式即可在 HTML 中使用,除非您有意使用 ASCII 字符集。转义命名实体,然后将整个字符串编码为 UTF-8 并像这样写出来,更简单、更高效。您可能应该声明 HTTP 标头或标记中使用的编码。
编辑:
是的。您可以使用 HTTP 标头强制执行 UTF-8 字符集,也可以通过元标记直接在 HTML 中指定它:
It is not necessary to convert Unicode characters to the
&#xxxx;
form to work in HTML unless you're deliberately using the ASCII charset. It's simpler and more efficient to escape named entities, then encode the whole string to UTF-8 and write it out like that. You should probably declare the encoding being used in the HTTP headers or in a<meta>
tag.EDIT:
Yes. You can either use HTTP headers to enforce a UTF-8 charset or specify it in the HTML directly via a meta tag:
撇开验证问题不谈,能够删除这些字符(无论如何都不能可靠地显示)而不必转义其他任何内容是很有用的。为此,我将以下函数添加到“lib/helpers.py”:
您可以通过编辑
environment.py
将其用作过滤器:然后它应该可用于您的模板:
Validation issues aside, it's useful to be able to remove these characters (which don't display reliably anyway) without necessarily escaping anything else. To this end I added the following function to `lib/helpers.py':
And you can make this available as a filter by editing
environment.py
:It should then be available to your templates: