def translate(self, tstring, domain=None, mapping=None): """ Translate a :term:`translation string` to the current language and interpolate any *replacement markers* in the result. The ``translate`` method accepts three arguments: ``tstring`` (required), ``domain`` (optional) and ``mapping`` (optional). When called, it will translate the ``tstring`` translation string to a ``unicode`` object using the current locale. If the current locale could not be determined, the result of interpolation of the default value is returned. The optional ``domain`` argument can be used to specify or override the domain of the ``tstring`` (useful when ``tstring`` is a normal string rather than a translation string). The optional ``mapping`` argument can specify or override the ``tstring`` interpolation mapping, useful when the ``tstring`` argument is a simple string instead of a translation string. Example:: from pyramid.18n import TranslationString ts = TranslationString('Add ${item}', domain='mypackage', mapping={'item':'Item'}) translated = localizer.translate(ts) Example:: translated = localizer.translate('Add ${item}', domain='mypackage', mapping={'item':'Item'}) """ if self.translator is None: self.translator = Translator(self.translations) return self.translator(tstring, domain=domain, mapping=mapping)
def test_translator_with_interpolation(self): translations = self._makeTranslations() from translationstring import Translator from translationstring import dugettext_policy from translationstring import TranslationString translator = Translator(translations, dugettext_policy) tstring = TranslationString('Visit ${url}', mapping={'url': 'url'}) result = translator(tstring) self.assertEqual(result, 'Besuchen url')
def test_translator_dugettext_policy(self): translations = self._makeTranslations() from translationstring import Translator from translationstring import dugettext_policy from translationstring import TranslationString translator = Translator(translations, dugettext_policy) tstring = TranslationString( 'Enter a comma separated list of user names.') result = translator(tstring) self.assertEqual(result, 'Eine kommagetrennte Liste von Benutzernamen.')
def test_translator_with_interpolation_partially_overridden_in_translate(self): translations = self._makeTranslations() from translationstring import Translator from translationstring import dugettext_policy from translationstring import TranslationString translator = Translator(translations, dugettext_policy) # Partial initial mapping tstring = TranslationString('${one} ${two} ${three}', mapping={ 'one': 'yksi', 'two': 'kaksi'}) # Partial override result = translator(tstring, mapping={'two': 'kakkonen'}) self.assertEqual(result, 'yksi kakkonen ${three}') # Make sure original mapping is not touched self.assertEqual(tstring.mapping, {'one': 'yksi', 'two': 'kaksi'})
def _makeOne(self, translations=None, policy=None): from translationstring import Translator return Translator(translations, policy)