by Jonathan Robson
internationalization = i + 18 letters + n = i18n
Internationalization is a means of making your software work in different languages.
localization = l + 10 letters + n = l10n
Localization is a means of making your software work in different regions.
| Returns UTF-8 bytestring | Returns a unicode string | Requires context message (also returns unicode) | |
|---|---|---|---|
| Without pluralization | gettext | ugettext | pgettext |
| With pluralization | ngettext | ungettext | npgettext |
| Lazy without pluralization | gettext_lazy | ugettext_lazy | pgettext_lazy |
| Lazy with pluralization | ngettext_lazy | ungettext_lazy | npgettext_lazy |
from django.utils.translation import ugettext as _
from django.http import HttpResponse
def my_view(request):
output = _('Welcome to my site.')
return HttpResponse(output)The underscore function _( ) is a common convention in gettext just to make things more concise and not let i18n get too much in the way, but it's not required.
from django.utils.translation import ugettext
from django.http import HttpResponse
def my_view(request):
output = ugettext('Welcome to my site.')
return HttpResponse(output)def my_view(request):
words = ['Welcome', 'to', 'my', 'site.']
output = _(' '.join(words))
return HttpResponse(output)def my_view(request):
sentence = 'Welcome to my site.'
output = _(sentence)
return HttpResponse(output)Don't do this:
Or this:
def my_view(request, m, d):
output = _('Today is %(month)s %(day)s.') % {'month': m, 'day': d}
return HttpResponse(output)If you need to include variables in your string, use gettext's interpolation functionality.
Use named parameters! Don't just use %s or %d!
from django.utils.translation import ungettext
from django.http import HttpResponse
def hello_world(request, count):
page = ungettext(
'there is %(count)d object',
'there are %(count)d objects',
count) % {
'count': count,
}
return HttpResponse(page)Do NOT programmatically add "s" to the end of things. (facepalm)
from django.utils.translation import pgettext
month = pgettext("month name", "May")def my_view(request):
# Translators: This message appears on the home page only
output = ugettext("Welcome to my site.")or...
https://docs.djangoproject.com/en/1.7/topics/i18n/translation/