This article mainly introduces some preliminary methods for string translation in the Django framework of Python. Django also provides the string detection tool to be translated, you can refer to the ugettext () function to specify a translation string. As a convention, short alias _ is used to introduce this function to save the input time.
In the following example, the text "Welcome to my site" is marked as a string to be translated:
from django.utils.translation import ugettext as _def my_view(request): output = _("Welcome to my site.") return HttpResponse(output)
Obviously, you can also not use aliases for encoding. The following example is the same as the previous two examples:
from django.utils.translation import ugettextdef my_view(request): output = ugettext("Welcome to my site.") return HttpResponse(output)
The translation string is equally valid for the calculated value. The following example is equivalent to the previous one:
def my_view(request): words = ['Welcome', 'to', 'my', 'site.'] output = _(' '.join(words)) return HttpResponse(output)
Translation is also effective for variables. Here is the same example:
def my_view(request): sentence = 'Welcome to my site.' output = _(sentence) return HttpResponse(output)
(In the above two examples, for using variables or computed values, note that Django's string to be translated detection tool, make-messages.py, will not be able to find these strings. Later, we will discuss more in makemessages .) The string you pass to _ () or gettext () can accept placeholders, which are specified by the syntax of the standard Python naming string. For example:
def my_view(request, m, d): output = _('Today is %(month)s %(day)s.') % {'month': m, 'day': d} return HttpResponse(output)
This technology allows the translation of specific languages to re-sort the text. For example, the English translation may be "Today is November 26. ", and a Spanish translation will be" Hoy es 26 de Noviembre. "use placeholders (months and dates) to exchange their locations.
For this reason, whenever you have more than one single parameter, you should use the named string to insert (for example, % (day) s) to replace location insertion (for example: % s or % d ). If you insert positions, the translation action cannot re-sort the placeholder text.