Formatter & Translations
We need the Formatter
and Translations
class and the parseLocale()
function to handle translations.
In the context of the DOM we can also use the getLocaleOfDocument()
method.
import {Translations} from '@schukai/monster/source/i18n/translations.mjs';
import {Formatter} from '@schukai/monster/source/text/formatter.mjs';
import {parseLocale} from '@schukai/monster/source/i18n/locale.mjs';
import {getLocaleOfDocument} from '@schukai/monster/source/dom/locale.mjs';
Let’s start with the function parseLocale()
. This function can create a Locale
object from a string.
So we can create the corresponding Locale
object from the string en_GB
.
const locale = parseLocale('en_GB')
// ↦ Locale {}
If we move in the browser, so we can also use the function getLocaleOfDocument()
.
This function returns a locale object as a result.
This function looks if the HTML tag <html lang="en">
has a lang
attribute.
If no locale is defined, the default value is assumed to be en
.
We now need an object with the translations. For this, we use the Translations
class.
We can either define the translations ourselves or load them via an API.
// define translations
const translation = new Translations(parseLocale('en-GB'));
translation.assignTranslations({
text1: 'hello world!',
text2: {
'one': 'click once',
'other': 'click ${n | tostring} times' // this is where the pipe comes in
}
});
// fetch from API
const translation = new Fetch('https://example.com/${language}.json')
.getTranslation('en-GB');
// ↦ https://example.com/en.json
If we now have a translation, we can now read the desired strings. For this
we use the method Translation.getText()
or the method Translation.getPluralRuleText()
for texts with more than one number.
const message = translation.getText('text1');
// -> hello world
To translate texts with number references, enter the desired number.
let n=1;
const message1 = translation.getPluralRuleText('text2', n);
// -> click once
n=2
const message2 = translation.getPluralRuleText('text2', n);
// -> click ${n} times
To replace the placeholder now, the formatter is used.
const text = new Formatter({n}).format(message2);
console.log(text)
// ↦ click 2 times
Finally, let’s take a look at the formatter class from the i18n module.
import {Formatter} from
"@schukai/monster/source/text/formatter.mjs";
A translation object can be passed directly to this class.
There is also the possibility to pass values in the format string.
// define translation
const translations = new Translations('en')
.assignTranslations({
// text with placeholder
message: "${animal} has eaten the ${food}!"
});
// without marker and inline values
new Formatter({}, translations).format("message::animal=dog::food=cake")
// ↦ dog has eaten the cake!