3

尽管提供了一种使用过滤器转义输出的好方法,但它们都没有做正确的事情。取字符串:

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 Con​​sortium 字符库,它留下未定义的(除其他外)65 个字符代码(包括 0 到 31 和 127 到 159)

这些似乎是错过的角色。有任何想法吗?

编辑

它似乎可以验证我是否离线使用该文件。这可能是内容类型问题吗?

4

2 回答 2

2

&#xxxx;除非您有意使用 ASCII 字符集,否则不必将 Unicode 字符转换为在 HTML 中工作的表单。转义命名实体更简单、更有效,然后将整个字符串编码为 UTF-8 并像这样写出来。您可能应该声明在 HTTP 标头或<meta>标签中使用的编码。

编辑:

它似乎可以验证我是否离线使用该文件。这可能是内容类型问题吗?

是的。您可以使用 HTTP 标头强制执行 UTF-8 字符集,也可以直接通过元标记在 HTML 中指定它:

<meta http-equiv="Content-Type" content="application/xhtml+xml;charset=utf-8" />
于 2010-01-24T03:40:11.053 回答
1

除了验证问题之外,能够删除这些字符(无论如何都不会可靠地显示)很有用,不必转义其他任何内容。为此,我在 `lib/helpers.py' 中添加了以下函数:

__sgml_invalid = re.compile(r'[\x82-\x8c\x91-\x9c\x9f]', re.UNICODE)

def sgmlsafe(text):
    lookup = {
        130:"&#8218;",    #Single Low-9 Quotation Mark
        131: "&#402;",    #Latin Small Letter F With Hook
        132:"&#8222;",    #Double Low-9 Quotation Mark
        133:"&#8230;",    #Horizontal Ellipsis
        134:"&#8224;",    #Dagger
        135:"&#8225;",    #Double Dagger
        136: "&#710;",    #Modifier Letter Circumflex Accent
        137:"&#8240;",    #Per Mille Sign
        138: "&#352;",    #Latin Capital Letter S With Caron
        139:"&#8249;",    #Single Left-Pointing Angle Quotation Mark
        140: "&#338;",    #Latin Capital Ligature OE
        145:"&#8216;",    #Left Single Quotation Mark
        146:"&#8217;",    #Right Single Quotation Mark
        147:"&#8220;",    #Left Double Quotation Mark
        148:"&#8221;",    #Right Double Quotation Mark
        149:"&#8226;",    #Bullet
        150:"&#8211;",    #En Dash
        151:"&#8212;",    #Em Dash
        152: "&#732;",    #Small Tilde
        153:"&#8482;",    #Trade Mark Sign
        154: "&#353;",    #Latin Small Letter S With Caron
        155:"&#8250;",    #Single Right-Pointing Angle Quotation Mark
        156: "&#339;",    #Latin Small Ligature OE
        159: "&#376;"     #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}
于 2010-01-24T05:17:11.790 回答