Use the function Ugettext () to specify a translation string. As a rule, use short aliases _ to introduce this function to save typing 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 encode without using aliases. 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 translated string is also 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 equally valid for variables. Here is a similar example:
def my_view (Request): sentence = ' Welcome to my site. ' Output = _ (sentence) return HttpResponse (output)
(in the two examples above, for the use of variables or computed values, one thing to note is that the Django String Detection Tool, make-messages.py, will not be able to find these strings.) Later, there will be more discussion in the makemessages. The string you pass to _ () or GetText () can accept placeholders that are specified by the Python standard-named string inserted in the syntax. For example:
def my_view (Request, M, D): output = _ (' Today is% (month) s% (day) s. ')% {' Month ': M, ' Day ': D} return HttpResponse (output)
This technique allows the text to be reordered in a language-specific translation. For example, an English translation might be "Today is November 26." and a Spanish translation would be "Hoy es-Noviembre." Use placeholders (month and date) to exchange their positions.
For this reason, whenever you have more than one single parameter, you should use a named string insert (for example:% (day) s) to replace the location insertion (for example:%s or%d). If you use position insertion, the translation action will not reorder the placeholder text.