Standalone API
For example:
If an unsupported locale is passed to i18n
, then the default messages are returned. Further, any messages not provided by the locale-specific bundle will also fall back to their defaults. As such, the default bundle should contain all message keys used by any of the locale-specific bundles.
import i18n, { setLocaleMessages } from '@dojo/framework/i18n/i18n';
import bundle from 'nls/main';
const partialMessages = { hello: 'Ahoj' };
setLocaleMessages(bundle, partialMessages, 'cz');
i18n(bundle, 'cz').then((messages) => {
console.log(messages.hello); // "Ahoj"
console.log(messages.goodbye); // "Goodbye" (defaults are used when not overridden)
});
Once locale dictionaries for a bundle have been loaded, they are cached and can be accessed synchronously via getCachedMessages
:
getCachedMessages
will look up the bundle’s supported locales
to determine whether the default messages should be returned. Locales are also normalized to their most specific messages. For example, if the ‘fr’ locale is supported, but ‘fr-CA’ is not, getCachedMessages
will return the messages for the ‘fr’ locale:
const frenchMessages = getCachedMessages(bundle, 'fr-CA');
console.log(frenchMessages.hello); // "Bonjour"
console.log(frenchMessages.goodbye); // "Au revoir"
const madeUpLocaleMessages = getCachedMessages(bundle, 'made-up-locale');
console.log(madeUpLocaleMessages.hello); // "Hello"
console.log(madeUpLocaleMessages.goodbye); // "Goodbye"
The current locale can be accessed via the read-only property i18n.locale
, which will always be either the locale set via switchLocale
(see below) or the systemLocale
.
The systemLocale
is also read-only, and its value is determined by the current execution environment in the following manner:
import i18n, { observeLocale, switchLocale, systemLocale } from '@dojo/framework/i18n/i18n';
import bundle from 'nls/bundle';
// Register an event listener
// handle locale change...
});
// Change the locale to German. The registered observer's callback will be called
// with the new locale.
switchLocale('de');
// The locale is again switched to German, but since the current root locale is
// already German, registered observers will not be notified.
switchLocale('de');
console.log(i18n.locale); // 'de'