Internationalization on Bitbucket

by Jonathan Robson

What is i18n and l10n?

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.

Django i18n functions

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

Usage

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)

Use string literals!

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:

Using variables

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!

Pluralization

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)

Context

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

Building translations

  1. Build django.po file for English
  2. Generate i18n.js file
  3. Build djangojs.po file for English
  4. Push .po files to Transifex for English
  5. Pull .po files from Transifex for other languages
  6. Merge with local .po files
  7. Compile .po files into .mo files
  8. Generate djangojs.js files

Further reading

https://docs.djangoproject.com/en/1.7/topics/i18n/translation/

Internationalization in Bitbucket

By Jonathan Robson