Coverage for tw2/core/mako_util.py : 78%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1import unicodedata
2from mako.runtime import Undefined
3from copy import copy
5from markupsafe import Markup
6try:
7 from html import escape
8except ImportError:
9 from cgi import escape
10import six
11#from mako.filters import xml_escape
13__all__ = ["attrs"]
15_BOOLEAN_ATTRS = frozenset(['selected', 'checked', 'compact', 'declare',
16 'defer', 'disabled', 'ismap', 'multiple',
17 'nohref', 'noresize', 'noshade', 'nowrap'])
20def attrs(context, args=None, attrs=None):
21 # Emulates Genshi's AttrsDirective (poorly)
22 if isinstance(args, list):
23 args = dict(args)
24 if not args:
25 args = {}
26 else:
27 args = copy(args)
28 if attrs:
29 args.update(attrs)
30 bools = _BOOLEAN_ATTRS
32 new_attrs = [six.u('%s="%s"') % (k, escape(six.text_type(k in bools and k or v), True))
33 for k, v in six.iteritems(args)
34 if (k not in bools and v is not None) or (k in bools and v)]
35 return Markup(six.u(" ").join(new_attrs))
38def compat(context, attr):
39 """ Backwards compatible widget attribute access.
41 In tw1, all template attributes looked like:
42 ${some_attribute}
44 Whereas in tw2 they look like:
45 ${w.some_attribute}
47 This is a *nuisance* if you want to reuse a template between tw1 and tw2
48 widgets. With this function you can write:
49 <%namespace name="tw" module="tw2.core.mako_util"/>
50 ${tw.compat(attr='some_attribute')}
51 or
52 ${tw._('some_attribute')}
54 Nice, right? :)
55 """
57 if not 'w' in context.keys():
58 # Must be tw1
59 return context.get(attr)
60 else:
61 # Must be tw2
62 return getattr(context.get('w'), attr)
65_ = compat # Just for shorthand