开发者

In Django, how to determine if translation for a given text is available?

开发者 https://www.devze.com 2023-01-23 15:57 出处:网络
I would like to determine, if there\'s a translation to current language for a given string. I\'d like to write something like:开发者_JAVA技巧

I would like to determine, if there's a translation to current language for a given string. I'd like to write something like:开发者_JAVA技巧

if not translation_available("my string"):
    log_warning_somewhere()

I didn't find anything appropriate. The ugettext function just returns the translation or the original string (if the translation isn't available) but without any option to determine if the translation is there or isn't.

Thanks.


For anyone looking for a hacky solution:

from django.utils.translation import trans_real

def custom_gettext(msg):
    # Returns None when a data translation is not found
    return trans_real._active.value._catalog.get(msg)  # noqa

if custom_gettext("my string") is None:
    log_something()


You can use polib for that: https://bitbucket.org/izi/polib/wiki/Home

Something along those (untested) lines of code:

import polib
po = polib.pofile('path/your_language.po')
text == 'Your text'
is_translated = any(e for e in po if e.msgid == text and (not e.translated() or 'fuzzy' in e.flags) and not e.obsolete)

This will give True when an active translation is available. 'e.translated()' alone returns True for both, fuzzy and/or obsolete phrases, too.


Since, as you say, ugettext will return the original string if no translation is available, can't you just compare the returned value with the original to see if they're identical?


def translation_available(msg): return ugettext(msg) == msg


Szymon's solution worked for me after a minor change:

from django.utils.translation import trans_real

def custom_gettext(msg):
    # Returns None when a data translation is not found
    return trans_real.catalog()._catalog.get(msg)  # noqa

if custom_gettext("my string") is None:
    log_something()
0

精彩评论

暂无评论...
验证码 换一张
取 消