简体   繁体   English

访问Django的ugettext_lazy的未翻译内容

[英]Access untranslated content of Django's ugettext_lazy

I'm looking for a sane way to get to the untranslated content of a ugettext_lazy ied string. 我正在寻找一种理智的方式来获取ugettext_lazy ied字符串的未翻译内容。 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_lazy ied string and the code that accesses it are miles appart. 当然,在实际代码中, ugettext_lazy ied字符串的定义和访问它的代码是里程数。

Another two options. 另外两个选择。 Not very elegant, but not private api and is not slow. 不是很优雅,但不是私人api,并不慢。

  • Number one, define your own ugettext_lazy: 第一,定义你自己的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 

This is the better version of your second solution 这是您的第二个解决方案的更好版本

from django.utils import translation

the_string = ugettext_lazy('the content')
with translation.override('en'):
    content = unicode(the_string)

You can do that (but you shouldn't): 你可以这样做(但你不应该这样做):

the_string = ugettext_lazy('the content')
the_string._proxy____args[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM