Internationalizing a Dojo application
Configuring supported application locales
An internationalized application should specify all its supported locales within its .dojorc
build configuration file. One locale should be designated as the primary/default locale for the application, with the remainder of the supported locales as secondary options that can be activated when required. This is done via the locale
property and supportedLocales
list within the build-app
section.
Note: Since the various formatters and parsers rely on locale-specific CLDR data, most of the functionality provided by @dojo/framework/i18n
requires at least a locale
to be set in the .dojorc
in order to function properly. For example, if no default locale
is specified, then only the default bundle messages will be returned and ICU message formatting will be disabled.
locale
: string- The primary locale supported by the application. That is, the default language that will be used if an override locale is not specified.
supportedLocales
: string[]- A list of additional locales that the application supports. These locales need to be activated to override the default
locale
, either implicitly through an application user’s language setting when running client-side, the process’ or host’s language setting when running server-side, or explicitly within the application itself.
- A list of additional locales that the application supports. These locales need to be activated to override the default
For example, with the following configuration, an application specifies that its default locale is English (en
), and that it supports Spanish (es
) and French (fr
) as additional locale choices:
.dojorc
{
"build-app": {
"locale": "en",
"supportedLocales": ["es", "fr"]
}
}
Creating i18n-aware widgets
Individual widgets can be internationalized by using the i18n
middleware from @dojo/framework/core/middleware/i18n
. Using the middleware adds some optional i18n-related properties to the widget property interface. The API for the i18n
middleware includes a method, localize(bundle)
to get the localized nls values given a message bundle and two methods that can be used to get and set the application’s locale details.
i18n
widget properties
locale
?: string- The locale for the widget.If not specified, then the root application locale or its override is assumed.If specified, the widget’s DOM node will have a
lang
property set to the locale.
- The locale for the widget.If not specified, then the root application locale or its override is assumed.If specified, the widget’s DOM node will have a
rtl
?: boolean- An optional flag indicating the widget’s text direction. If
true
, then the underlying DOM node’sdir
property is set to"rtl"
. If it isfalse
, then thedir
property is set to"ltr"
. Otherwise, the property is not set.
- An optional flag indicating the widget’s text direction. If
i18nBundle
?:Bundle<Messages>
|Map<Bundle<Messages>, Bundle<Messages>>
- An optional override for the default language bundle passed to the
localizeBundle
method. If the override contains amessages
object, then it will completely replace the underlying default language bundle that the widget may be using. If the override only contains alocales
object, a new bundle will be created with the additional locale loaders specified in the override.
- An optional override for the default language bundle passed to the
i18n
localize()
method
Widgets can pass in their default language bundle into the localize
method to have the bundle localized appropriately given the widget’s locale
property.
If the bundle supports the widget’s current locale, but those locale-specific messages have not yet been loaded, then a bundle of blank message values is returned. Alternatively, the localize
method accepts a second boolean argument, which, when true
, causes the default messages to be returned instead of the blank bundle. The widget will be invalidated once the locale-specific messages have been loaded, triggering a re-render with the localized message content.
The object returned by localize
contains the following properties and methods:
messages
- An object containing the localized message key-value pairs. If the messages have not yet loaded, then
messages
will be either a blank bundle or the default messages, depending upon howlocalize
was called.
- An object containing the localized message key-value pairs. If the messages have not yet loaded, then
isPlaceholder
- A boolean property indicating whether the returned messages are the actual locale-specific messages (
false
) or just the placeholders used while waiting for the localized messages to finish loading (true
). This is useful to prevent the widget from rendering at all if localized messages have not yet loaded.
- A boolean property indicating whether the returned messages are the actual locale-specific messages (
format(key: string, replacements: { [key: string]: string })
- A method that accepts a message key as its first argument and an object of replacement values as its second. For example, if the bundle contains
greeting: 'Hello, {name}!'
, then callingformat('greeting', { name: 'World' })
would return'Hello, World!'
.
- A method that accepts a message key as its first argument and an object of replacement values as its second. For example, if the bundle contains
An example of using all features returned by localize
:
nls/en/MyI18nWidget.ts
export default {
messages: {
hello: 'Welcome to the shop',
purchaseItems: 'Please confirm your purchase',
itemCount: 'Purchase {count} items'
}
};
widgets/MyI18nWidget.tsx
import { create, tsx } from '@dojo/framework/core/vdom';
import i18n from '@dojo/framework/core/middleware/i18n';
import Label from '@dojo/widgets/label';
import Button from '@dojo/widgets/button';
import greetingsBundle from '../nls/en/MyI18nWidget';
const factory = create({ i18n });
export default factory(function MyI18nWidget({ middleware: { i18n } }) {
// Load the "greetings" messages for the current locale. If the locale-specific
// messages have not been loaded yet, then the default messages are returned,
// and the widget will be invalidated once the locale-specific messages have
// loaded.
const { format, isPlaceholder, messages } = i18n.localize(greetingsBundle);
// In many cases it makes sense to postpone rendering until the locale-specific messages have loaded,
// which can be accomplished by returning early if `isPlaceholder` is `true`.
if (isPlaceholder) {
return;
}
return v('div', { title: messages.hello }, [
w(Label, {}, [
// Passing a message string to a child widget.
messages.purchaseItems
]),
w(Button, {}, [
// Passing a formatted message string to a child widget.
format('itemCount', { count: 2 })
])
]);
});
Note that with this pattern it is possible for a widget to obtain its messages from multiple bundles. When favoring simplicity, however, it is recommend that widgets are limited to a single bundle wherever possible.
I18nMixin
for class-based widgets
Individual class-based widgets can be internationalized by adding the I18nMixin
mixin from @dojo/framework/core/mixins/I18n
. This mixin adds the same optional i18n-related widget properties as the i18n
middleware, and provides a localizeBundle
method which is used to localize an imported message bundle to the widget’s current locale.
localizeBundle()
method
Widgets can pass in their default language bundle into the localizeBundle
method to have the bundle localized appropriately given the widget’s locale
property.
If the bundle supports the widget’s current locale, but those locale-specific messages have not yet been loaded, then a bundle of blank message values is returned. Alternatively, the localizeBundle
method accepts a second boolean argument, which, when true
, causes the default messages to be returned instead of the blank bundle. The widget will be invalidated once the locale-specific messages have been loaded, triggering a re-render with the localized message content.
The object returned by localizeBundle
contains the following properties and methods:
messages
- An object containing the localized message key-value pairs. If the messages have not yet loaded, then
messages
will be either a blank bundle or the default messages, depending upon howlocalizeBundle
was called.
- An object containing the localized message key-value pairs. If the messages have not yet loaded, then
isPlaceholder
- A boolean property indicating whether the returned messages are the actual locale-specific messages (
false
) or just the placeholders used while waiting for the localized messages to finish loading (true
). This is useful to prevent the widget from rendering at all if localized messages have not yet loaded.
- A boolean property indicating whether the returned messages are the actual locale-specific messages (
format(key: string, replacements: { [key: string]: string })
- A method that accepts a message key as its first argument and an object of replacement values as its second. For example, if the bundle contains
greeting: 'Hello, {name}!'
, then callingformat('greeting', { name: 'World' })
would return'Hello, World!'
.
- A method that accepts a message key as its first argument and an object of replacement values as its second. For example, if the bundle contains
An example of using all features returned by localizeBundle
:
nls/en/MyI18nWidget.ts
export default {
messages: {
hello: 'Welcome to the shop',
purchaseItems: 'Please confirm your purchase',
itemCount: 'Purchase {count} items'
}
};
widgets/MyI18nWidget.ts
import WidgetBase from '@dojo/framework/core/WidgetBase';
import { v, w } from '@dojo/framework/core/vdom';
import I18nMixin from '@dojo/framework/core/mixins/I18n';
import Label from '@dojo/widgets/label';
import Button from '@dojo/widgets/button';
import greetingsBundle from '../nls/en/MyI18nWidget';
export default class MyI18nWidget extends I18nMixin(WidgetBase) {
render() {
// Load the "greetings" messages for the current locale. If the locale-specific
// messages have not been loaded yet, then the default messages are returned,
// and the widget will be invalidated once the locale-specific messages have
// loaded.
const { format, isPlaceholder, messages } = this.localizeBundle(greetingsBundle);
// In many cases it makes sense to postpone rendering until the locale-specific messages have loaded,
// which can be accomplished by returning early if `isPlaceholder` is `true`.
if (isPlaceholder) {
return;
}
return v('div', { title: messages.hello }, [
w(Label, {}, [
// Passing a message string to a child widget.
messages.purchaseItems
]),
w(Button, {}, [
// Passing a formatted message string to a child widget.
format('itemCount', { count: 2 })
])
]);
}
}
Providing locale data to i18n-aware widgets
Locale details also need to be managed via a Dojo registry when applications use i18n-aware class-based widgets (specifically, those that use I18nMixin
). This applies to any such widgets contained within the application itself or as part of an external dependency - including any widgets used from Dojo’s @dojo/widgets
suite. Locale data is injected into all such widgets through the Dojo registry system; these widgets will be invalidated and re-rendered with updated locale data when the application locale is changed.
This mechanism is enabled through registerI18nInjector
, a convenience method provided by @dojo/framework/core/mixins/I18n
. Calling this method will register the i18n
injector within a specific registry instance. Typically this is done at application bootstrap, where the i18n injector is registered against the global registry passed to the renderer.mount()
method.
main.ts
import renderer from '@dojo/framework/core/vdom';
import { w } from '@dojo/framework/core/vdom';
import Registry from '@dojo/framework/core/Registry';
import { registerI18nInjector } from '@dojo/framework/core/mixins/I18n';
import App from './App';
const registry = new Registry();
registerI18nInjector({ locale: 'us', rtl: false }, registry);
const r = renderer(() => w(App, {}));
r.mount({ registry });
Changing locales
The i18n
middleware can be used to change the application’s locale. Calling i18n.set({ locale: string, rtl: boolean });
will propagate the new locale to all widgets that are using the i18n
middleware, as well as any using I18nMixin
(assuming registerI18nInjector has previously been setup in the application).
Example usage
The following example shows an i18n-aware widget that renders two buttons that allow switching the application locale between English and French.
import { create, tsx } from '@dojo/framework/core/vdom';
import i18n from '@dojo/framework/core/middleware/i18n';
import nlsBundle from '../nls/main';
const factory = create({ i18n });
export default factory(function LocaleChanger({ middleware: { i18n } }) {
const { messages } = localize(nlsBundle);
return (
<div>
<button
onclick={() => {
i18n.set({ locale: 'en' });
}}
>
English
</button>
<button
onclick={() => {
i18n.set({ locale: 'fr' });
}}
>
French
</button>
<div>{messages.greetings}</div>
</div>
);
});
Overriding locales and bundles per-widget
Widgets that use either the i18n
middleware or I18nMixin
can have their i18n widget properties overridden when instantiated by a parent. This can be useful when rendering several widgets with different locales in a single application (that is, using multiple locales within one application), as well as to override the set of messages a third-party widget may be using and align them within the context of your application.
Each i18n-aware widget can have its own independent locale by providing a locale
widget property. If no locale
property is set, then the default locale is assumed.
The widget’s default bundle can also be replaced by passing an i18nBundle
widget property. Dojo recommends against using multiple bundles in the same widget, but there may be times when an application needs to consume a third-party widget that does make use of more than one bundle. As such, i18nBundle
can also be a Map
of default bundles to override bundles.
An example of overriding bundles within child widgets:
import { Bundle } from '@dojo/framework/i18n/i18n';
// A complete bundle to replace WidgetA's message bundle
import overrideBundleForWidgetA from './nls/widgetA';
// Bundles for WidgetB
import widgetB1 from 'third-party/nls/widgetB1';
import overrideBundleForWidgetB from './nls/widgetB';
// WidgetB uses multiple bundles, but only `thirdy-party/nls/widgetB1` needs to be overridden
const overrideMapForWidgetB = new Map<Bundle<any>, Bundle<any>>();
map.set(widgetB1, overrideBundleForWidgetB);
export class MyWidget extends WidgetBase {
protected render() {
return [
w(WidgetA, {
i18nBundle: overrideBundleForWidgetA
}),
w(WidgetB, {
i18nBundle: overrideMapForWidgetB
})
];
}
}
Default locale
The locale that an i18n-aware widget will use is determined in the following order until a value is found, depending on which i18n features an application makes use of:
Order | I18n capability | Locale setting |
---|---|---|
1 | I18nMixin /i18n middleware | An explicit override provided via the widget’s locale property. |
2 | I18nMixin /i18n middleware and i18n injector | A locale that has been selected or changed within the application |
3 | I18nMixin /i18n middleware and i18n injector | The default locale set when initially registering the i18n injector. |
4 | .dojorc | A user’s current locale, such as their browser language setting, if the locale is in the application’s list of build-app .supportedLocales . |
5 | .dojorc | The application’s default locale specified in build-app .locale . |
6 | @dojo/framework/i18n | An explicit locale set via Dojo i18n’s switchLocale method. |
7 | @dojo/framework/i18n | The systemLocale for the current execution environment. |