I was working with an open-source project (made in Django). I couldn't understand what pgettext_lazy
is used for. Can you please tell me
pgettext_lazy(..)
[Django-doc] is a function that is used to translate text. The Django documentation has a section on translation [Django-doc] that discusses this.
pgettext_lazy
is a lazy variant of pgettext
. This is a function that makes context-aware translations [Django-doc]. Context-aware translations deal with the fact that a word can be translated in multiple ways. For example May
can be translated as the name of a month, or a verb.
We can make it clear how to translate it by adding a "context marker", and thus call the translation with:
from django.utils.translation import pgettext month = pgettext("month name", "May")
In your .po
file(s), the files you use to define translations, you can then add the context marker:
msgctxt "month name"
msgid "May"
msgstr ""
You can make translations in the views in the language that is activated, but you can not just define that translation in for example the help_text
of a model. Indeed, if you would call pgettext(..)
in a models.py
file. It would translate the help_text
in the language that is active at that time. But if later a user with a different language uses that help_text
, it would not be translated in the other language.
By making the translation lazy, the process of translation is postponed until a str(..)
is called on the result. That way, if you render the lazy object in a template it will be translated in the language of the user.
You can find more information on this in the Translation section of the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With