i18n and translations

Mark up translations in templates by using an i18n: namespaced element or attribute.

The i18n:translate directive causes text to be tagged for translation:

<h1 i18n:translate="">Main heading</h1>

If a value is given in the i18n:translate attribute this is used as the message for translation in preference to any content of the element:

<h1 i18n:translate="Main heading">Oh freddled gruntbuggly</h1>

The i18n:comment directive allows you to supply a comment for translators. As a shortcut this attribute can be used on its own without a corresponding i18n:translate:

<p i18n:comment="note to translators">Welcome friend!</p>

Interpolations inside translations are automatically included in the extracted message. Simple variable expressions are passed through unchanged:

<p i18n:translate="">Last updated at ${time}</p>

For longer expressions, use i18n:name to simplify the translation message. The following will be extracted as Last updated at ${when}

<p i18n:trans="">Last updated at
    <i18n:name name="when">${format_timedelta(now - time)}</p>

Extracting message catalogs

Piglet includes a babel extractor. Add the following or similar to your babel.ini to extract messages from Piglet templates:

[piglet:**/templates/**.html]

Runtime configuration

The translations_factory argument to piglet.loader.TemplateLoader should be used to provide a gettext object to generated templates. This must be a function that takes no arguments and returns a gettext object:

from piglet import TemplateLoader
from gettext import GNUTranslations

def get_translations():
    return GNUTranslations(somefile)

loader = TemplateLoader(search_path=['templates'],
                        translations_factory=get_translations)

Here’s an example for use with Django’s translation machinery:

from piglet import TemplateLoader
import django.utils.translation

def get_translations():
    return django.utils.translation

loader = TemplateLoader(search_path=['templates'],
                        translations_factory=get_translations)