1. ollyc
  2. fresco-i18n

Overview

HTTPS SSH

fresco-i18n - internationalization for fresco sites

Example initialization code

from pkg_resources import resource_filename
import fresco
import fresco_i18n
import gettext


# This function should return a stdlib gettext translation object
# loaded for the given langauges.
def get_translations(languages):
    return gettext.translation('my_translation_domain',
                               resource_filename(__name__, 'locale'),
                               languages)



app = fresco.FrescoApp()
app.add_middleware(fresco_i18n.I18NMiddleware,
                   available_languages=['de', 'en', 'fr']
                   default_language=['en'],
                   get_translations=get_translations,
                   saver=fresco_i18n.CookieLocales(cookie_path='/'),
                   loaders=[fresco_i18n.PathLocales(),
                            "saver",
                            fresco_i18n.AcceptLanguage()],
                   save_strategy='explicit')

Let's unpick that:

get_translations is a function that returns a regular (standard library) gettext translations object

The fresco_i18n.I18NMiddleware does language detection and preference saving and takes a few different options:

saver=fresco_i18n.CookieLocales(cookie_path='/')

Language preference is persisted in a cookie.

loaders=[fresco_i18n.PathLocales(),
         "saver",
         fresco_i18n.QueryStringLoader('hl')],
         fresco_i18n.AcceptLanguage()],
         save_strategy='explicit')

The active translation will be detected from, in order of priority:

  1. The first URL path segment, eg /en/… or /fr/….
  2. saver: any value previously persisted in the saver option (in this case a CookieLocales object)
  3. A query parameter named hl (eg /about?hl=fr)
  4. The Accept-Language request header
save_strategy='explicit'

This argument determines when the saver is invoked (eg a cookie set in the case of CookieLocales).

Possible values are:

  • explicit: only save the preference when your application explicitly calls environ['i18n.set_language'](language, save=True).
  • once: the language will be be saved if environ['i18n.set_language'] is called and the preference has not previously been saved.
  • always: the language will be be saved every time environ['i18n.set_language'] is called and the language differs from any currently saved language.

Examples of translating text in python code:

# For translateable strings defined at module level or anywhere else
# outside of a request context, use fresco_i18n.translations_lazy
from fresco_i18n import translations_lazy

_ = translations_lazy.gettext

hello_message = _('Hello world')
# For strings defined within a request context (eg inside a view function)
# use fresco_i18n.translations
from fresco_i18n import translations as _

_ = translations.gettext

def view():
    return Response(_('Hello world!'))