How can I join lazy translation in Django?

我的梦境 提交于 2019-12-02 00:21:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!