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