Alex Rivera | Logout

Access untranslated content of Django's ugettext_lazy

Asked 2011-02-28T15:17:42.763
14

I'm looking for a sane way to get to the untranslated content of a ugettext_lazyied string. I found two ways, but I'm not happy with either one:

the_string = ugettext_lazy('the content')
the_content = the_string._proxy____args[0] # ewww!

or

from django.utils.translation import activate, get_language
from django.utils.encoding import force_unicode

the_string = ugettext_lazy('the content')
current_lang = get_language()
activate('en')
the_content = force_unicode(the_string)
activate(current_lang)

The first piece of code accesses an attribute that has been explicitly marked as private, so there is no telling how long this code will work. The second solution is overly verbose and slow.

Of course, in the actual code, the definition of the ugettext_lazyied string and the code that accesses it are miles appart.

Edit
Report

1 Answer

6

Another two options. Not very elegant, but not private api and is not slow.

  • Number one, define your own ugettext_lazy:

    from django.utils import translation
    
    def ugettext_lazy(str):
        t = translation.ugettext_lazy(str)
        t.message = str
        return t
    
    >>> text = ugettext_lazy('Yes')
    >>> text.message
    "Yes"
    >>> activate('lt')
    >>> unicode(text)
    u"Taip"
    >>> activate('en')
    >>>> unicode(text)
    u"Yes"
    
  • Number two: redesign your code. Define untranslated messages separately from where you use them:

    gettext = lambda s: s
    some_text = gettext('Some text')
    
    lazy_translated = ugettext_lazy(text)
    untranslated = some_text
    
answered 2011-03-10T21:05:51.127

Your Answer