0

I am currently relying on django translations and I am curious to know if there is a better way to pick msgid for translations rather than the usual approach.

For instance:

In order to mark something for translation you have to do the following.

variable_name = _("Some Name")

and Django picks the msgid in the following way

msgid "Some Name"
msgstr "Some Name"

I currently would like to see if there is a way in which I can either pass a key to gettext

_("my string", "my_key")

or

An implementation in which the variable name becomes the msgid automatically when django picks up the variable.

msgid "variable_name"
msgstr "Some Name"

Any idea or suggestion would be really helpful.

Ahsan
  • 31
  • 1
  • 6

1 Answers1

0

The msgid can't be overwritten, it's a source string for translation. But you can use the django.utils.translation.pgettext() function to provide a contextual information:

from django.utils.translation import pgettext

# Use pgettext to specify a custom ID and the original string
print(pgettext("variable_name", "Some Name"))

This will appear in the .po file as:

msgctxt "variable_name"
msgid "Some Name"
msgstr ""

In case your string needs pluralization, there is a django.utils.translation.npgettext() function:

from django.utils.translation import npgettext

def show_items(count):
    message = npgettext(
        'variable_name',
        'You have one apple',
        'You have {count} apples',
        count
    )
    print(message.format(count=count))

show_items(1) # Output: You have one apple
show_items(3) # Output: You have 3 apples

This will appear in the .po file as:

msgctxt "variable_name"
msgid "You have one apple"
msgid_plural "You have {count} apples"
Andrii Bodnar
  • 1,672
  • 2
  • 17
  • 24