问题
I need to use lazy translation but also I need to make translation - how to deal with?
This code is doing what I need:
print ugettext_lazy('Hello world!')
Now I want join two lazy translations together and translate it separately (I now that will not work and why but want to have two translation strings).
print ugettext_lazy('Hello world!') + ' ' + ugettext_lazy('Have a fun!')
I can do such code but it generates more translation than is need.
print ugettext_lazy('Hello world! Have a fun!')
Is it possible to have two translation strings and lazy translation?
回答1:
Since django 1.11 string-concat is deprecated, and format_lazy should be used instead
from django.utils.text import format_lazy
from django.utils.translation import ugettext_lazy
name = ugettext_lazy('John Lennon')
instrument = ugettext_lazy('guitar')
result = format_lazy('{} : {}', name, instrument)
回答2:
I don't think you can, otherwise it would result in another string being translated...
Here's an example taken from the docs. There's no mention on joining 2 translation files in one, so I assume it cannot be done, but I can be wrong.
This is the correct way of doing it
https://docs.djangoproject.com/en/1.7/topics/i18n/translation/#joining-strings-string-concat
from django.utils.translation import string_concat
from django.utils.translation import ugettext_lazy
...
name = ugettext_lazy('John Lennon')
instrument = ugettext_lazy('guitar')
result = string_concat(name, ': ', instrument)
来源:https://stackoverflow.com/questions/29252312/how-can-i-join-lazy-translation-in-django