Hello,
Django’s translation is awesome… except when it comes to translating python strings with variables inside them.
Here is the doc Translation | Django documentation | Django
And as much as I tried I could not get it to work lazily with c-strings or f-strings.
Here is a simple troublesome example:
from django.utils.translation import gettext_lazy as _
a = _("Welcome to Django") # works
user_name = "aaa" # variable from somewhere
b = _("Dear %(user)s. Welcome to Django!") % {"user": username} # is not lazy
We could fix this by making another gettext-like function:
from django.utils.functional import lazy
from django.utils.translation import gettext
get_c_string_lazy = lazy(lambda message, keys={}: gettext(message) % keys)
Then this works:
from django.utils.translation import get_c_string_lazy as _
a = _("Welcome to Django") # works
user_name = "aaa" # variable from somewhere
b = _("Dear %(user)s. Welcome to Django!", {"user": username}) # is now lazy
What do you think? Am I missing something?
Could that break the pluralization support?
Two notes:
- It seems this would actually just be an improvement to the standard gettext_lazy, it does not have to be a new function
- The motivation to use c-string instead of f-string is that makemessages for blocktrans in templates will also turn variables into c-string style strings inside the translation files. So this helps with consistency.