Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: keep lazy translation when composing translated strings

In Django, I'm happily using ugettext_lazy to pospone the translation of a string only when its representation is needed.

The problem is that when I concatenate a lazy string to a normal string or when I use its methods (e.g. capitalize() ), the string is evaluated and I loose lazy translation.

E.g.

label = ugettext_lazy('my label')   #This is lazy
label_concat = label + ' some other string'   #'label_concat' contains transalted 'label'
label_cap = label.capitalize()  #'label_cap' contains transalted 'label'

#Set language
...

print label    #Translated
print label_cap  #Not translated

I know that this is the normal behaviour of Django but I wonder if someone has resolved this issue.

like image 482
Don Avatar asked Nov 09 '11 16:11

Don


People also ask

What is Gettext_lazy in Django?

gettext_lazy is a callable within the django. utils. translation module of the Django project.

How do I translate text in Django?

Use the function django. utils. translation. gettext_noop() to mark a string as a translation string without translating it.

Which among the given below internationalization function in Django marks a string as a translation string without actually translating it at that moment?

Lazy Translation utils. translation. ugettext_lazy() to translate strings lazily – when the value is accessed rather than when the ugettext_lazy() function is called. In this example, ugettext_lazy() stores a lazy reference to the string – not the actual translation.


1 Answers

For concatenating, you can use string_concat (up to 1.10)/format_lazy (from 1.11) which creates a lazy object

If you wish to implement lazy capitalize, use django.utils.functional.lazy decorator. See string_concat implementation.

like image 74
bmihelac Avatar answered Oct 11 '22 01:10

bmihelac