Skip to content

Internationalisation

James Livesey edited this page Feb 2, 2021 · 1 revision

About this feature

Internationalisation is important since it allows your app to be used by users which speak multiple languages. This feature is important even if you don't intend to distribute your app globally, since implementing its features in your code future-proofs it if your app were to go global in the future.

Locale data format

Translation string scripts belong in lang/ directory and include one call to lang.load.

The string translations are held in a JavaScript object as the data argument like so:

lang.load("en_GB", {
    name: "Français (France)",
    nameShort: "Français",
    textDirection: "ltr", // Would be "rtl" for some languages which are written right-to-left, such as Arabic
    strings: {
        "Hello, world!": "Bonjour le monde !",
        "Hello, {0}!": "Bonjour, {0} !" // Positional arguments are supported, eg. here {0} could reference somebody's name
    }
});

Usage in code

In HTML, an @ symbol should be prepended before all strings that should be translated:

<p>@Hello, world!</p>

The string will automatically be translated.

In JavaScript, the _ command should be used:

console.log(_("Hello, world!"));

Important: Don't forget to do this wherever you're writing a string that'll appear in the UI!

Reference

lang.load

Load a given locale data object for a locale code. This is primarily used by files in the lang/ directory.

Parameters

  • code (string): The locale code to apply the locale data to
  • data (object): The locale data to load

lang.use

Switch to a given locale.

Parameters

  • code (string): The locale code to switch to

Example

lang.use("en_GB"); // Switch to English (United Kingdom)

lang.getLocale

Get the current locale code.

Example

console.log(lang.getLocale()); // Logs "en_GB" if your system language is set to English (United Kingdom)

lang.format

Format a date or a number in the given locale.

Parameters

  • data (Number || Date): The data to format
  • code (string): The locale code used when formatting the data
  • options (object = {}): The optional formatting options

Example

console.log(lang.format(new Date(), "en_GB")); // Logs "02/02/2021, 14:58:23"

lang.translate = _

Translates a given string into the currently-selected locale. _ is equivalent to this command and is convenient due to its length.

Parameters

  • string (string): The string to translate
  • arguments (object = {}): Any positional arguments to interpolate into the translation
  • useLocaleFormats (boolean = true): Whether positional arguments should be formatted using lang.format

Example

console.log(_("Hello, world!")); // Logs "Bonjour le monde !" if French is the currently-selected locale and "Hello, world!" has a translation entry
console.log(_("Hello, {0}!"), ["James"])); // Logs "Hello, James!" if English (United Kingdom) is the currently-selected locale and "Hello, {0}!" has a translation entry