fluent module

class fluent_anvil.fluent.Fluent

Bases: object

Anvil interface for fluent and some convenience functions.

The class interfaces with a JavaScript library that initializes fluent, feeds fluent the .ftl files matching the selected locale and provides some convenience functions like obtaining the user’s preferred locale.

The function most you will use most often is Fluent.format().

Example

The following will initialize fluent with Mexican Spanish locale and return the translation stored with message id “hello”. The name is given so that fluent may use it as a placeable. The last parameter is a list of fallback locales that will be iterated through if the given message id is not available for the “es_MX” locale:

fluent = Fluent(
    "localization/{locale}/main.ftl", "es_MX", ["es_ES", "en_US"]
)
print(fluent.format("hello", name="John"))
__init__(templates: list = '{locale}/main.ftl', root: str = './_/theme/localization/', index: str = 'index.lst')

Initialize Fluent.

Parameters:
  • root – String path to the directory with the localization files.

  • index – Path to the index.lst file inside the root directory, e.g. “index.lst”. The file contains the language tags of all available locales, e.g. de en-US en-GB fr

  • templates – Template string or list of template strings to the .ftl files, inside the given root directory. For example, “{locale}/main.ftl”. You can only use the {locale} placeholder. It will contain the locale with underscore, e.g. “de_DE” instead of “de-DE”, because Anvil does not support hyphens for directory names.

configure(locales: list = None, templates: list = None, root: str = None, index: str = None, datetime_options: dict = None, number_options: dict = None)

Configure the translation system.

Parameters:
  • locales – A list of IETF language tags to set the translation system to in order of preference. The most appropriate option will be chosen automatically depending on which locales are actually available.

  • templates – Template paths or list of template paths to the .ftl files, inside the given root directory. For example, “{locale}/main.ftl”. You can only use the {locale} placeholder. It will contain the locale with underscore, e.g. “de_DE” instead of “de-DE”, because Anvil does not support hyphens for directory names.

  • root – Path to the directory with localization files, e.g. “./_/theme/localization/”.

  • index – Path to the index.lst file inside the root directory, e.g. “index.lst”. The file contains the language tags of all available locales, e.g. de en-US en-GB fr

  • datetime_options – Defines default options to use when formatting dates using the Fluent.format() method without any additional options. See documentation of the Fluent.format() method for a (possibly incomplete) list of options or the documentation of JavaScript’s Intl.DateTimeFormat object (which is used internally) for a complete list of options.

  • number_options – Defines default options to use when formatting numbers using the Fluent.format() method without any additional options. See documentation of the Fluent.format() method for a (possibly incomplete) list of options or the documentation of JavaScript’s Intl.NumberFormat object (which is used internally) for a complete list of options.

format(message, *args, **kwargs)

Return a translation for the given message id / number / date and variables.

You can use this function in multiple ways by providing:

  • A single message id (with optional keyworded variables to pass on to Fluent)

  • An arbitrary number of Message instances.

  • A number (for displaying it in a localized format)

  • A date, time, or datetime object (for displaying it in a localized format)

In case of a date, time, or datetime object you may also provide additional options as keyworded arguments (kwargs). Since JavaScript’s Intl.DateTimeFormat functionality is used, the options are the same. You can find the complete documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat Some of these are:

  • dateStyle: “full”, “long”, “medium”, “short” (the level of verbosity regarding the date)

  • timeStyle: “full”, “long”, “medium”, “short” (the level of verbosity regarding the time)

  • hour12: True or False (whether to use 12-hour time or 24-hour-time)

  • TimeZoneName: “short”, “long”, “shortOffset”, “longOffset”, “shortGeneric”, “longGeneric” (the way of displaying the time zone)

  • year: “2-digit”, “numeric”,

  • month: “2-digit”, “numeric”, “narrow”, “short”, “long”,

  • day: “2-digit”, “numeric”,

  • dayPeriod: “narrow”, “short”, “long”

  • hour: “2-digit”, “numeric”,

  • minute: “2-digit”, “numeric”,

  • second: “2-digit”, “numeric”,

  • fractionalSecondDigits: 1, 2, 3

  • weekday: “narrow”, “short”, “long”

  • era: “narrow”, “short”, “long”

In case of a number, you may also provide these options as keyworded arguments as well. Since JavaScript’s Intl.NumberFormat functionality is used, the options are the same. You can find the complete documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat Some of these are:

  • notation: “standard”, “scientific”, “engineering”, “compact”

  • numberingSystem: arab”, “arabext”, “bali”, “beng”, “thai”, “tibt”, etc.

  • signDisplay: “auto”, “always”, “exceptZero”, “negative”, “never”

  • useGrouping: “always”, “auto”, false, “min2”

  • roundingMode: “ceil”, “floor”, “expand”, “trunc”, “halfCeil”, “halfEven”, etc.

  • currencySign: “accounting”, “standard”

Examples

You get the translation for a single message id like this:

fl = Fluent("localization/{locale}/main.ftl", "es_MX", ["en_US"])
print(fl.format("hello", name="John"))

Alternatively, you can provide an arbitrary number of Message instances:

fl = Fluent("localization/{locale}/main.ftl", "es_MX", ["en_US"])
print(fl.format(
    Message("hello", name="world"),
    Message(self.label, "text", "hello", name="John"),
    Message("welcome", name="john")
))

You can format a number:

fl = Fluent("localization/{locale}/main.ftl", "es_MX", ["en_US"])
print(fl.format(32000))

You can format a date:

fl = Fluent("localization/{locale}/main.ftl", "es_MX", ["en_US"])
exdate = datetime.fromisoformat('2011-11-04T03:05:23')
print(fl.format(date))

You can format a date and provide additional options:

fl = Fluent("localization/{locale}/main.ftl", "es_MX", ["en_US"])
exdate = datetime.fromisoformat('2011-11-04T03:05:23')
print(fl.format(date, dateStyle="full", timeStyle="short"))
Parameters:
  • message – message id (as string) or Message instance to return a translation for.

  • args – An arbitrary number of additional Message instances (not message ids).

  • kwargs – Keyworded variables to pass on to Fluent (only in case parameter message is a string).

Returns: A translation string in case a string message id is given. If Message

instances are given, a list of translations in the same order.

format_table(data, columns: list, options: dict = None, **kwargs)

Translate a list of dictionaries.

This is meant for tabular data which consists of a list of dictionaries. The keys in these dictionaries represent the columns of the table. This method will translate the columns given in the “columns” parameter. Empty cells in the table will be ignored.

Parameters:
  • data – The list of dictionaries to translate.

  • columns – A list of dictionary keys, i.e., column names to translate. Other dictionary keys will not be touched.

  • options

    Dictionary with which one can provide options for value columns that contain numbers, dates, etc. Example:

    {
        "My Date Column": {"dateStyle": "medium"},
        "My Number Column": {"notation": "scientific"}
    }
    

  • kwargs – Optional keyworded variables to pass on to fluent (e.g., for placeables or selectors).

get_currency_name(code, style=('dialect', 'long'))

Returns the translated name of the given currency / currencies.

The name of the given currency code (e.g., “USD”, “EUR”) is returned in the language fluent has been configured for.

Parameters:
  • code – The currency code (e.g., “USD”, “EUR”, “CNY”, etc.) or list of currency codes to get the translated name for.

  • style – Style constant. Can be one of the following: STYLE_DIALECT_LONG, STYLE_DIALECT_SHORT, STYLE_DIALECT_NARROW, STYLE_STANDARD_LONG, STYLE_STANDARD_SHORT, STYLE_STANDARD_NARROW.

get_currency_options(style=('dialect', 'long'), translatable_only: bool = False) dict

Return all currencies and their translated name for display.

Parameters:
  • style – Style constant. Can be one of the following: STYLE_DIALECT_LONG, STYLE_DIALECT_SHORT, STYLE_DIALECT_NARROW, STYLE_STANDARD_LONG, STYLE_STANDARD_SHORT, STYLE_STANDARD_NARROW.

  • translatable_only – If True, skip options that cannot be adequately translated. Set to False to return all options even if the name is only available in English.

get_language_options(style=('dialect', 'long'), translatable_only: bool = False) dict

Return all language tags and their translated name for display.

Parameters:
  • style – Style constant. Can be one of the following: STYLE_DIALECT_LONG, STYLE_DIALECT_SHORT, STYLE_DIALECT_NARROW, STYLE_STANDARD_LONG, STYLE_STANDARD_SHORT, STYLE_STANDARD_NARROW.

  • translatable_only – If True, skip options that cannot be adequately translated. Set to False to return all options even if the name is only available in English.

get_locale_name(locale, style=('dialect', 'long'))

Returns the translated name of the given locale(s).

The name of the given locale is returned in the language fluent has been configured for.

Parameters:
  • locale – The locale or list of locales to get the translated name for.

  • style – Style constant. Can be one of the following: STYLE_DIALECT_LONG, STYLE_DIALECT_SHORT, STYLE_DIALECT_NARROW, STYLE_STANDARD_LONG, STYLE_STANDARD_SHORT, STYLE_STANDARD_NARROW.

get_locale_options(style=('dialect', 'long'), translatable_only: bool = False) dict

Return complete locale tags (e.g., en-US) and their translated name.

Parameters:
  • style – Style constant. Can be one of the following: STYLE_DIALECT_LONG, STYLE_DIALECT_SHORT, STYLE_DIALECT_NARROW, STYLE_STANDARD_LONG, STYLE_STANDARD_SHORT, STYLE_STANDARD_NARROW.

  • translatable_only – If True, skip options that cannot be adequately translated. Set to False to return all options even if the name is only available in English.

get_region_name(code, style=('dialect', 'long'))

Returns the translated name of the given regions(s).

The name of the given region code is returned in the language fluent has been configured for.

Parameters:
  • code – The region code (e.g., “AT”, “US”, “GB”, etc.) or list of region codes to get the translated name for.

  • style – Style constant. Can be one of the following: STYLE_DIALECT_LONG, STYLE_DIALECT_SHORT, STYLE_DIALECT_NARROW, STYLE_STANDARD_LONG, STYLE_STANDARD_SHORT, STYLE_STANDARD_NARROW.

get_region_options(style=('dialect', 'long'), translatable_only: bool = False) dict

Return all region tags and their translated name for display.

Parameters:
  • style – Style constant. Can be one of the following: STYLE_DIALECT_LONG, STYLE_DIALECT_SHORT, STYLE_DIALECT_NARROW, STYLE_STANDARD_LONG, STYLE_STANDARD_SHORT, STYLE_STANDARD_NARROW.

  • translatable_only – If True, skip options that cannot be adequately translated. Set to False to return all options even if the name is only available in English.

get_script_name(code, style=('dialect', 'long'))

Returns the translated name of the given script(s).

The name of the given script code is returned in the language fluent has been configured for.

Parameters:
  • code – The script code (e.g., “Arab”, “Latn”, etc.) or list of script codes to get the translated name for.

  • style – Style constant. Can be one of the following: STYLE_DIALECT_LONG, STYLE_DIALECT_SHORT, STYLE_DIALECT_NARROW, STYLE_STANDARD_LONG, STYLE_STANDARD_SHORT, STYLE_STANDARD_NARROW.

get_script_options(style=('dialect', 'long'), translatable_only: bool = False) dict

Return all script tags and their translated name for display.

Parameters:
  • style – Style constant. Can be one of the following: STYLE_DIALECT_LONG, STYLE_DIALECT_SHORT, STYLE_DIALECT_NARROW, STYLE_STANDARD_LONG, STYLE_STANDARD_SHORT, STYLE_STANDARD_NARROW.

  • translatable_only – If True, skip options that cannot be adequately translated. Set to False to return all options even if the name is only available in English.

STYLE_DIALECT_LONG = ('dialect', 'long')
STYLE_DIALECT_NARROW = ('dialect', 'narrow')
STYLE_DIALECT_SHORT = ('dialect', 'short')
STYLE_STANDARD_LONG = ('standard', 'long')
STYLE_STANDARD_NARROW = ('standard', 'narrow')
STYLE_STANDARD_SHORT = ('standard', 'short')
SUPPORTED_VALUE_TYPES = (<class 'datetime.date'>, <class 'datetime.datetime'>, <class 'datetime.time'>, <class 'int'>, <class 'float'>)
property index

Return the relative path to the index.lst file.

property locale: list

Returns the current locale including fallbacks in order of preference.

property root

Returns the path to the localization directory.

property templates

Returns the templates paths for the fluent message files.