尽管提供了一种使用过滤器转义输出的好方法,但它们都没有做正确的事情。 拿字符串:
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 Consortium字符集,并且保留未定义的(其中包括)65个字符代码(0到31(含)和127到159(含))
这些似乎是错过的人物。有什么想法吗?
修改
似乎验证我是否脱机使用该文件。这可能是内容类型问题吗?
答案 0 :(得分:2)
除非您故意使用ASCII字符集,否则无需将Unicode字符转换为&#xxxx;
表单以使用HTML。转义命名实体更简单,更有效,然后将整个字符串编码为UTF-8并将其写出来。您应该声明在HTTP标头或<meta>
标记中使用的编码。
修改强>
似乎验证我是否脱机使用该文件。这可能是内容类型问题吗?
是。您可以使用HTTP标头强制执行UTF-8字符集,也可以直接通过元标记在HTML中指定它:
<meta http-equiv="Content-Type" content="application/xhtml+xml;charset=utf-8" />
答案 1 :(得分:1)
除了验证问题之外,能够删除这些字符(无论如何都不能可靠地显示)是有用的。没有必然会逃避其他任何事情。为此,我将以下函数添加到`lib / helpers.py':
__sgml_invalid = re.compile(r'[\x82-\x8c\x91-\x9c\x9f]', re.UNICODE)
def sgmlsafe(text):
lookup = {
130:"‚", #Single Low-9 Quotation Mark
131: "ƒ", #Latin Small Letter F With Hook
132:"„", #Double Low-9 Quotation Mark
133:"…", #Horizontal Ellipsis
134:"†", #Dagger
135:"‡", #Double Dagger
136: "ˆ", #Modifier Letter Circumflex Accent
137:"‰", #Per Mille Sign
138: "Š", #Latin Capital Letter S With Caron
139:"‹", #Single Left-Pointing Angle Quotation Mark
140: "Œ", #Latin Capital Ligature OE
145:"‘", #Left Single Quotation Mark
146:"’", #Right Single Quotation Mark
147:"“", #Left Double Quotation Mark
148:"”", #Right Double Quotation Mark
149:"•", #Bullet
150:"–", #En Dash
151:"—", #Em Dash
152: "˜", #Small Tilde
153:"™", #Trade Mark Sign
154: "š", #Latin Small Letter S With Caron
155:"›", #Single Right-Pointing Angle Quotation Mark
156: "œ", #Latin Small Ligature OE
159: "Ÿ" #Latin Capital Letter Y With Diaeresis
}
return __sgml_invalid.sub(lambda x: lookup[ord(x.group())], text)
您可以通过修改environment.py
:
config['pylons.app_globals'].mako_lookup = TemplateLookup(
...
imports=[....,'from appname.lib.helpers import sgmlsafe',...]
然后它应该可用于您的模板:
${c.content|n,sgmlsafe}