Mako的Filtering and Buffering讨论过滤器以及如何使用它们。但是有可能访问过滤器本身使用的方法吗?
我想正确地转义将有条件地呈现的属性中的值。基本上我想这样做:
<element ${'attribute="${value | h}"' if value else ''}>
这显然无效,因为您无法在字符串中嵌套表达式。所以我试过了:
<element ${'attribute="{}"'.format(h(value)) if value else ''}>
但是,NameError: 'h' is not defined
失败了。我想避免这样做:
<element
% if value:
attribute="${value | h}"
% endif
>
或者:
<element ${'attribute="' if value else ''}${value or '' | h}${'"' if value else ''}>
我知道我可以使用多种不同的方法之一来转义HTML属性:cgi.escape(value, True)
,xml.sax.saxutils.quoteattr(value)
(除了它确定了你的引号),或markupsafe.escape(value)
(第三 - 派对)。如果可能的话,我更愿意使用Mako使用的方法。有没有办法使用某种查找工具访问Mako的内置h
?
答案 0 :(得分:0)
h
转义过滤器映射到mako.filters.html_escape()
。如,
from mako.filters import html_escape as h
转义过滤器映射到mako.filters.DEFAULT_ESCAPES
:
DEFAULT_ESCAPES = {
'x': 'filters.xml_escape',
'h': 'filters.html_escape',
'u': 'filters.url_escape',
'trim': 'filters.trim',
'entity': 'filters.html_entities_escape',
'unicode': 'unicode', # str in python 3
'decode': 'decode',
'str': 'str',
'n': 'n'
}
n
和decode
过滤器是特殊条件,不会映射到特定功能。其他是mako.filters
的内置函数或函数。这些可以通过两种方式评估:
潜在的危险方式:
def lookup_escape(name):
from mako import filters
return eval(filters.DEFAULT_ESCAPES[name])
更安全的方式:
import functools
try:
import builtins
except ImportError:
import __builtin__ as builtins
import mako.filters
def lookup_escape(name):
path_parts = mako.filters.DEFAULT_ESCAPES[name].split('.')
for module in (mako, builtins):
try:
return functools.reduce(getattr, path_parts, module)
except AttributeError:
pass
raise LookupError(name)
最后,可以使用所需的转义过滤器:
h = lookup_escape('h')