Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is pgettext_lazy in Django?

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

  1. What is pgettext_lazy?
  2. Usage of pgettext_lazy?
like image 716
MayankBudhiraja Avatar asked Jan 05 '20 13:01

MayankBudhiraja


1 Answers

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.

like image 143
Willem Van Onsem Avatar answered Nov 18 '22 02:11

Willem Van Onsem