Package genshi :: Package filters :: Module i18n :: Class Translator

Class Translator

                    object --+    
                             |    
template.base.DirectiveFactory --+
                                 |
                                Translator

Can extract and translate localizable strings from markup streams and templates.

For example, assume the following template:

>>> tmpl = MarkupTemplate('''<html xmlns:py="http://genshi.edgewall.org/">
...   <head>
...     <title>Example</title>
...   </head>
...   <body>
...     <h1>Example</h1>
...     <p>${_("Hello, %(name)s") % dict(name=username)}</p>
...   </body>
... </html>''', filename='example.html')

For demonstration, we define a dummy gettext-style function with a hard-coded translation table, and pass that to the Translator initializer:

>>> def pseudo_gettext(string):
...     return {
...         'Example': 'Beispiel',
...         'Hello, %(name)s': 'Hallo, %(name)s'
...     }[string]
>>> translator = Translator(pseudo_gettext)

Next, the translator needs to be prepended to any already defined filters on the template:

>>> tmpl.filters.insert(0, translator)

When generating the template output, our hard-coded translations should be applied as expected:

>>> print(tmpl.generate(username='Hans', _=pseudo_gettext))
<html>
  <head>
    <title>Beispiel</title>
  </head>
  <body>
    <h1>Beispiel</h1>
    <p>Hallo, Hans</p>
  </body>
</html>

Note that elements defining xml:lang attributes that do not contain variable expressions are ignored by this filter. That can be used to exclude specific parts of a template from being extracted and translated.

Nested Classes

Inherited from template.base.DirectiveFactory: __metaclass__

Instance Methods
 
__init__(self, translate=NullTranslations(), ignore_tags=frozenset([QName('script'), QName('style'), QName('http://www...., include_attrs=frozenset(['abbr', 'alt', 'label', 'prompt', 'standby', 'summa..., extract_text=True)
Initialize the translator.
 
__call__(self, stream, ctxt=None, translate_text=True, translate_attrs=True)
Translate any localizable strings in the given stream.
 
extract(self, stream, gettext_functions=('_', 'gettext', 'ngettext', 'dgettext', 'dngettext', 'ugettex..., search_text=True, comment_stack=None)
Extract localizable strings from the given template stream.
 
get_directive_index(self, dir_cls)
Return a key for the given directive class that should be used to sort it among other directives on the same SUB event.
 
setup(self, template)
Convenience function to register the Translator filter and the related directives with the given template.

Inherited from template.base.DirectiveFactory: get_directive

Inherited from object: __delattr__, __format__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__

Class Variables
  directives = [('domain', <class 'genshi.filters.i18n.DomainDir...
A list of (name, cls) tuples that define the set of directives provided by this factory.
  IGNORE_TAGS = frozenset([QName('script'), QName('style'), QNam...
  INCLUDE_ATTRS = frozenset(['abbr', 'alt', 'label', 'prompt', '...
  NAMESPACE = Namespace('http://genshi.edgewall.org/i18n')
Properties

Inherited from object: __class__

Method Details

__init__(self, translate=NullTranslations(), ignore_tags=frozenset([QName('script'), QName('style'), QName('http://www...., include_attrs=frozenset(['abbr', 'alt', 'label', 'prompt', 'standby', 'summa..., extract_text=True)
(Constructor)

 
Initialize the translator.
Parameters:
  • translate - the translation function, for example gettext or ugettext.
  • ignore_tags - a set of tag names that should not be localized
  • include_attrs - a set of attribute names should be localized
  • extract_text - whether the content of text nodes should be extracted, or only text in explicit gettext function calls
Overrides: object.__init__

Note: Changed in 0.6: the translate parameter can now be either a gettext-style function, or an object compatible with the NullTransalations or GNUTranslations interface

__call__(self, stream, ctxt=None, translate_text=True, translate_attrs=True)
(Call operator)

 

Translate any localizable strings in the given stream.

This function shouldn't be called directly. Instead, an instance of the Translator class should be registered as a filter with the Template or the TemplateLoader, or applied as a regular stream filter. If used as a template filter, it should be inserted in front of all the default filters.

Parameters:
  • stream - the markup event stream
  • ctxt - the template context (not used)
  • translate_text - whether text nodes should be translated (used internally)
  • translate_attrs - whether attribute values should be translated (used internally)
Returns:
the localized stream

extract(self, stream, gettext_functions=('_', 'gettext', 'ngettext', 'dgettext', 'dngettext', 'ugettex..., search_text=True, comment_stack=None)

 

Extract localizable strings from the given template stream.

For every string found, this function yields a (lineno, function, message, comments) tuple, where:

  • lineno is the number of the line on which the string was found,
  • function is the name of the gettext function used (if the string was extracted from embedded Python code), and
  • message is the string itself (a unicode object, or a tuple of unicode objects for functions with multiple string arguments).
  • comments is a list of comments related to the message, extracted from i18n:comment attributes found in the markup
>>> tmpl = MarkupTemplate('''<html xmlns:py="http://genshi.edgewall.org/">
...   <head>
...     <title>Example</title>
...   </head>
...   <body>
...     <h1>Example</h1>
...     <p>${_("Hello, %(name)s") % dict(name=username)}</p>
...     <p>${ngettext("You have %d item", "You have %d items", num)}</p>
...   </body>
... </html>''', filename='example.html')
>>> for line, func, msg, comments in Translator().extract(tmpl.stream):
...    print('%d, %r, %r' % (line, func, msg))
3, None, u'Example'
6, None, u'Example'
7, '_', u'Hello, %(name)s'
8, 'ngettext', (u'You have %d item', u'You have %d items', None)
Parameters:
  • stream - the event stream to extract strings from; can be a regular stream or a template stream
  • gettext_functions - a sequence of function names that should be treated as gettext-style localization functions
  • search_text - whether the content of text nodes should be extracted (used internally)
Notes:
  • Changed in 0.4.1: For a function with multiple string arguments (such as ngettext), a single item with a tuple of strings is yielded, instead an item for each string argument.
  • Changed in 0.6: The returned tuples now include a fourth element, which is a list of comments for the translator.

get_directive_index(self, dir_cls)

 

Return a key for the given directive class that should be used to sort it among other directives on the same SUB event.

The default implementation simply returns the index of the directive in the directives list.

Parameters:
  • dir_cls - the directive class
Returns:
the sort key
Overrides: template.base.DirectiveFactory.get_directive_index
(inherited documentation)

setup(self, template)

 
Convenience function to register the Translator filter and the related directives with the given template.
Parameters:

Class Variable Details

directives

A list of (name, cls) tuples that define the set of directives provided by this factory.
Value:
[('domain', <class 'genshi.filters.i18n.DomainDirective'>),
 ('comment', <class 'genshi.filters.i18n.CommentDirective'>),
 ('msg', <class 'genshi.filters.i18n.MsgDirective'>),
 ('choose', <class 'genshi.filters.i18n.ChooseDirective'>),
 ('singular', <class 'genshi.filters.i18n.SingularDirective'>),
 ('plural', <class 'genshi.filters.i18n.PluralDirective'>)]

IGNORE_TAGS

Value:
frozenset([QName('script'),
           QName('style'),
           QName('http://www.w3.org/1999/xhtml}script'),
           QName('http://www.w3.org/1999/xhtml}style')])

INCLUDE_ATTRS

Value:
frozenset(['abbr',
           'alt',
           'label',
           'prompt',
           'standby',
           'summary',
           'title'])