14. I18n mechanism

14.1. Overview

Kay has a almost full stack i18n feature including extracting messages from the source, adding new language to your app, updating and compiling the message catalogs and a handlers for javascript gettext implementation. This feature is basicaly based on the jinja2’s i18n feature, so it is a good idea to refer to jinja2’s documentation hosted at:

http://jinja.pocoo.org/2/documentation/

Kay automatically detects user’s language by parsing Accept-Language header sent by user’s browser. You can also create a link for setting preffered language in user’s cookie which overrides Accept-Language setting.

14.2. Marking your messages

You can mark your messages for translation in python code as following:

from kay.i18n import gettext as _
_('Hello')

You can mark your messages for translation in templates as following:

<p>{{ _('Hello') }}</p>
<p>{% trans %}Hello{% endtrans %}

14.3. Extracting messages

You can extract the messages from myapp application and create the template catalog file as following:

$ python manage.py extract_messages myapp

The extract_messages subcommand accepts optional --domain parameter. The value for this parameter must be messages or jsmessages.

14.4. Adding translations

You can add new Japanese translations from the template like:

$ python manage.py add_translations myapp -l ja

14.5. Updating messages

You can update your translations with updated translation template as following:

$ python manage.py update_translations myapp -l ja

14.6. Compiling messages

You can compile all of your translations under myapp application as following:

$ python manage.py compile_translations myapp

14.8. I18n in Javascript

You can add a handler for pseudo javascript gettext to myproject/urls.py as following:

from kay.routing import (
  ViewGroup, Rule
)
view_groups = [
  ViewGroup(
    Rule('/_ah/queue/deferred', endpoint='deferred',
      view='kay.handlers.task.task_handler'),
    Rule('/maintenance_page', endpoint='_internal/maintenance_page',
      view='kay._internal.views.maintenance_page'),
    Rule('/_i18n.js', endpoint='i18n_js',
      view='kay.views.i18n.javascript_catalog',
      defaults={'packages':('myapp','kay')})
)]

Include it in index.html:

<script src="{{ url_for('i18n_js') }}"></script>

Put your javascript code in your application directory(e.g. myapp/static/myapp.js) like:

document.getElementById('dynamic').innerHTML = gettext('Hello');

Add static handler entry to your app.yaml like:

handlers:
- url: /static
  static_dir: myapp/static

Then you can extract and add messages for specific language(ja in this example) by:

$ python manage.py extract_messages myapp -d jsmessages
$ python manage.py add_translations myapp -l ja