-
Notifications
You must be signed in to change notification settings - Fork 27
Translations
(Using gettext and Jinja2)
Say you want to mark the following text as translatable in a template:
<body> <p>My name is {{ vars.name }}. This is my <em>awesome</em> content</p> <p>This content will be translated on the page.</p> </body>
Use the _(...)
syntax (for more information see the documentation on Jinja2's i18n extension):
<body> {{ _('<p>My name is %(name)s. This is my <em>awesome</em> content</p>')|format(name=vars.name) }} {{ _('<p>This content will be translated on the page.</p>') }} </body>
This syntax is preferred over Jinja's {% trans %}...{% endtrans %}
syntax because the utility to extract translatable string from source (see below) will automatically recognize the _(...)
syntax. It is possible to recognize either using Babel, but we do not have the bandwidth to figure out and set up an additional system right now.
When you've identified the strings to translate, and you're ready to start translating, run the xgettext
to extract those strings from your source (for Mac, refer to the installation instructions). Use the following commands:
xgettext -L Python -d messages --from-code=utf-8 -o i18n/en_TEST/LC_MESSAGES/messages.pot templates/*.html
For each language that you want to support, create a directory, such as:
mkdir -p i18n/lang_LOC/LC_MESSAGES/ cp i18n/messages.pot i18n/lang_LOC/LC_MESSAGES/messages.po
Where lang_LOC
should be replaced with the language and the locale, such as en_US
or es_MX
. Now copy the template translations file to the specific language/locale directory that you've created. If a file called messages.po
already exists, you may need to reconcile the content in that file with the messages in the new template. You don't want to copy over all of your existing translations! But if no such file exists, simple run:
cp i18n/messages.pot i18n/lang_LOC/LC_MESSAGES/messages.po
Fill in the translation files. You will see two identifiers in the file: msgid
and msgstr
. Each msgid
is an exact string extracted from the code. These exact strings are found and replaced during translation so DO NOT MANUALLY CHANGE THESE VALUES. Also, be aware that if you change the text in the code that you will need to rerun the xgettext
to extract the new strings. The translated string will go into the corresponding msgstr
.
After the strings in a messages.po
file have been translated, the file must be "compiled":
msgfmt -o i18n/lang_LOC/LC_MESSAGES/messages.mo i18n/lang_LOC/LC_MESSAGES/messages.po
For now, you must do this for each language/locale.