1 """Functions supporting translation of strings in Kid templates
2 """
3
4 from kid.parser import START, TEXT, END
5 from turbogears import config
6
7
8 from turbogears.i18n.tg_gettext import plain_gettext as gettext
9
10
12 """Translates the text of element plus the text of all child elements.
13
14 If 'attr' is present this is used to provide the locale name; if not then the
15 value provided by 'get_locale' is used. For example::
16
17 <div lang="">
18 this is a test
19 <a href="de">testing</a>
20 </div>
21
22 The string 'this is a test' is rendered by the locale provided by
23 'get_locale', the string 'testing' by the German locale.
24
25 Possible use in Kid template::
26
27 <?python
28 from turbogears.i18n import translate
29 ?>
30 <translate xmlns:py="http://purl.org/kid/ns#"
31 py:match="'lang' in item.attrib"
32 py:replace="translate(item)" />
33 <h1 lang="">Welcome!</h1>
34
35 @param item: element to be translated
36 @type item: ElementTree element
37
38 @param attr: attribute name used to store locale, if any
39 @type attr: str
40
41 """
42 if attr is None:
43 attr = config.get('i18n.templateLocaleAttribute', 'lang')
44
45 translate_all(item, item.get(attr), attr)
46 return item
47
48
49 -def __translate_text(text, lang):
50 prefix = ''
51 postfix = ''
52 if len(text) > 0 and text[0].isspace():
53 prefix = text[0]
54
55 if len(text) > 1 and text[-1].isspace():
56 postfix = text[-1]
57 return prefix + gettext(text.strip(), lang) + postfix
58
59
61 """Recursive function to translate all text in child elements.
62
63 @param tree: parent ElementTree element
64 @param lang: language setting
65 @param attr: attribute name used to store locale
66
67 """
68 if tree.text:
69 tree.text = __translate_text(tree.text, lang)
70
71 if tree.tail and not inroot:
72
73 tree.tail = __translate_text(tree.tail, lang)
74
75 for element in tree:
76
77 if element.get(attr):
78 lang = element.get(attr)
79 translate_all(element, lang, attr, False)
80
81
83 """Kid template filter translating all elements matching lang attribute.
84
85 The name of of the attribute is set in the configuration as
86 'i18n.templateLocaleAttribute' and defaults to 'lang'.
87
88 """
89 lang_attr = config.get('i18n.templateLocaleAttribute', 'lang')
90 locales = [locale]
91
92 for ev, item in stream:
93
94 if ev == START:
95 lang = item.get(lang_attr)
96 if lang:
97 locale = lang
98 locales.append(lang)
99
100 elif ev == TEXT:
101 prefix = ''
102 postfix = ''
103 if len(item) > 0 and item[0] == ' ':
104 prefix = ' '
105
106 if len(item) > 1 and item[-1] == ' ':
107 postfix = ' '
108
109 text = item.strip()
110 if text:
111 item = gettext(text, locale)
112 item = prefix + item + postfix
113
114 elif ev == END:
115 if item.get(lang_attr):
116 locales.pop()
117 locale = locales[-1]
118
119 yield (ev, item)
120