Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gettext for specific locales

I can get the translation in current locale using.

from django.utils.translation import ugettext as _
_("password")

However in my code (a form to be specific) I want to get the translation in a specific language. I want to be able to say.

ugettext_magic("de", "password")

I already have the strings translated in the languages I need.

like image 261
shabda Avatar asked Dec 05 '13 17:12

shabda


People also ask

How does gettext () work?

Gettext works by, first, generating a template file with all the strings to be translated directly extracted from the source files, this template file is called a . pot file which stands for Portable Object Template.

What is gettext package?

gettext utilities are a set of tools that provides a framework to help other packages produce multi-lingual messages. The minimum version of the gettext utilities supported is 0.19.

What is PHP gettext?

October 28, 2020 · 16 min read. GNU gettext is a package that offers to programmers, translators and even users a well integrated set of tools that provide a framework within which other free packages may produce multi-lingual messages.


2 Answers

Context manager django.utils.translation.override activates a new language on enter and reactivates the previous active language on exit

from django.utils import translation

def get_translation_in(language, s):
    with translation.override(language):
        return translation.gettext(s)

print(get_translation_in('de', 'text'))
like image 170
python273 Avatar answered Oct 28 '22 11:10

python273


There is a workaround:

from django.utils import translation
from django.utils.translation import ugettext

def get_translation_in(string, locale):
    translation.activate(locale)
    val = ugettext(string)
    translation.deactivate()

print get_translation_in('text', 'de')

Or simply:

gettext.translation('django', 'locale', ['de'], fallback=True).ugettext('text')
like image 33
Amir Ali Akbari Avatar answered Oct 28 '22 10:10

Amir Ali Akbari