Internationalisation (I18N)

How A Visitor Requests A Locale

A visitor of your site may request a particular locale by either the language settings in her browser, or by appending the query field _LOCALE_ to the URL, e.g.

You may specify the languages of your site in the site’s rc file (file rc.yaml in the site’s root directory), or you may allow all languages:

# This is a list of available languages, or [ '*' ]
# e.g. [ en, de, fr ]
i18n.avail_languages: [ it, fr, de, zh, ah ]
# This is the default language. It is used if the one given by the user
# could not be matched to a valid locale.
i18n.default_language: en

Localised Formatting

You have access to the matched locale from a template as locale. locale.language tells you the language name, and locale.territory tells you the territory (if set). See the Babel docs about Locale for details.

Additionally, bfmt provides you a formatter initialised with the current locale. Use it like this: {{, format='d. MMMM y')}}. See the Babel docs about Formatter for details. Here are examples concerning formatting of dates and numbers. See also the Unicode Locale Data Markup Language (LDML) about formatting patterns for dates and numbers.

Content Negotiation

Let’s say, the address shall provide an article in different languages.

In the folder content/animals create a file bees.yaml and bees.jinja2 as usual. But now, you write your articles into separate files, e.g. bees-en.jinja2 for the English version, bees-it.jinja2 for Italian and so on.

Put this in the main file (bees.jinja2):

{% block content %}
    {% if locale.language == 'it' %}
        {% include "bees-it.jinja2" %}
    {% elif locale.language == 'fr' %}
        {% include "bees-fr.jinja2" %}
    {% else %}
        {# This will be the default #}
        {% include "bees-en.jinja2" %}
    {% endif %}
{% endblock %}

Translated Strings

To provide translated strings, you may use the load_config() function. Write a mapping of a slug to a string in a particular language into a YAML file, one file per language, like so:


greeting: Hallo Welt


greeting: Hello World

Then load the messages into your template:

{% if locale.language == 'de' %}
    {% set msgs = load_config("messages-de.yaml") %}
{% elif locale.language == 'fr' %}
    {% set msgs = load_config("messages-fr.yaml") %}
{% else %}
    {# This will be the default #}
    {% set msgs = load_config("messages-en.yaml") %}
{% endif %}

{% block content %}
    <p>In your language, you greet: {{msgs['greeting']}}
{% endblock %}

Table Of Contents

Previous topic


Next topic


This Page