Search code examples
djangointernationalizationtranslationgettextlazy-evaluation

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.


Solution

  • 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.