我们将Django用于Speedy Net and Speedy Match(当前是Django 1.11.17,由于我们的要求之一django-modeltranslation,我们无法升级到较新版本的Django)。我在用上下文翻译字符串时遇到问题。我们主要根据上下文使用上下文来翻译字符串,具体取决于用户的性别,尽管英语字符串是相同的,但这在希伯来语等语言中的翻译方式也有所不同。例如,我有以下代码:
raise ValidationError(pgettext_lazy(context=self.instance.get_gender(), message="You can't change your username."))
(您可以在https://github.com/speedy-net/speedy-net/blob/staging/speedy/core/accounts/forms.py上看到它)
问题在于manage.py makemessages
在这里无法识别上下文。我们发现一种解决方法是将这些文本手动包含在我们根本不使用的文件中,例如__translations.py
或__translations.html
(您可以在https://github.com/speedy-net/speedy-net/blob/staging/speedy/core/__translations/__translations.py和https://github.com/speedy-net/speedy-net/blob/staging/speedy/core/__translations/__translations.html上看到它们),然后我们可以在上下文中包含相同的字符串:
要么:
pgettext_lazy(context="female", message="You can't change your username.")
pgettext_lazy(context="male", message="You can't change your username.")
pgettext_lazy(context="other", message="You can't change your username.")
或者:
{% trans "You can't change your username." context 'female' %}
{% trans "You can't change your username." context 'male' %}
{% trans "You can't change your username." context 'other' %}
但这是很多工作,我们在代码中每个字符串有4次(不包括翻译),维护这样的代码非常困难。就像我说的那样,这些文件根本没有使用,它们仅用于./make_all_messages.sh
才能正常工作。所以我的问题是-是否有办法将所有可能的上下文作为列表传递给manage.py makemessages
?例如,向pgettext_lazy
添加另一个参数,或添加manage.py makemessages
将读取的特定注释?我检查了一下,目前在这个项目中我们使用带有上下文的翻译大约100次,而仅仅为了manage.py makemessages
的工作而生成所有这些代码(100 * 3次)将是很多工作。
顺便说一句,方法get_gender()
始终返回以下字符串之一:“ female”,“ male”或“ other”。还有另一种方法get_match_gender()
,它返回相同的值。
是否可以将上下文“ other”定义为默认值,所以如果传递了不同的上下文(或不传递任何上下文)并且没有给定上下文的翻译,将使用“ other”吗?
对了,有人问过这个问题吗?有什么我不知道的解决方案吗?