如何在mako中正确转义输出(对于XHTML)?

时间:2010-01-24 03:23:35

标签: python xhtml unicode escaping mako

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

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(含))

这些似乎是错过的人物。有什么想法吗?

修改

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

2 个答案:

答案 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:"&#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}