WCI18n
WCI18n
is a lightweight i18n
solution for web components, in API it is quite similar to Polymer.AppLocalizeBehavior
but it is approaching the problem from a different angle.
WCI18n
assumes native support for the following two APIs:
Promise
fetch
If you don't have access to these two APIs in your target browser you will need to load them. Some quality polyfills can be found below:
There are a couple of distinct design differences between WCI18n
and Polymer.AppLocalizeBehavior
Specifically:
- There is only 1 language allowed across the entire application
- Each registered custom element defines (and fetches) its own locales, there is no support for a single locale file
- Each component will fetch only the locales it needs for the current language (meaning that for production, inlining a formatted locale object is advisable)
Example Usage
Basic Usage
WCI18n
is included and used in your component as follows:
<!-- Use the provided `i18n` function --> i18n('key')
You can inject a translation object by passing a formatted locales object to the WCI18n
function.
Formatted Object
{
"en": {
"key": "value"
},
"fr": {
"key": "valeur"
}
}
Example Injection
<!-- Use the provided `i18n` function --> i18n('key')
String Interpolation
Currently this component does not use the native Intl
object and the IntlMessageFormat
standards for legacy browser support. However
basic string interpolation is supported via 2 means:
key
->val
sequential string params- String format object
For example, if you take the following format string:
I love to take my {noun} to the {place}
You could do interpolation either of the following ways:
i18n('key', 'noun', 'cat', 'place', 'groomer');
i18n('key', { "noun": "cat", "place": "groomer" })
Both will create the following string:
I love to take my cat to the groomer
Global Config
Language
In addition to the typical component setup wc-i18n
provides some addition functions that you can use to configure the language of your application
Global Preset
By pre-defining the window.WCI18n
object you can create a new default language for your application.
This can be an easy way to set consistent global languages across multiple pages
Example:
Define WCI18n <!-- Web Components --> ...
Global Setter
The WCI18n
object now also exposes a setLanguage
function that can be called to set the language to a given locale.
Example:
windowWCI18n; //- Sets language to 'ko'
Bugs/Comments
Please feel free to leave a github issue if there is a bug or feedback on how to improve this solution