Translation

The Translation class encapsulates strings for a specific locale. It is used to translate strings into a specific language and country.

import {Translation} from '@schukai/monster/source/i18n/translation.mjs';

const translation = new Translation("en-US");
translation.set("hello", "Hello World!");

// plural rules
translation.setText("text6", {
    "zero": "There are no files on Disk.",
        "one": "There is one file on Disk.",
        "other": "There are files on Disk.",
    "default": "There are files on Disk."
});

If you want to assign a complete translation object, you can use the assignTranslations() method.

translation.assignTranslations({
    "hello": "Hello World!",
    "text6": {
        "zero": "There are no files on Disk.",
        "one": "There is one file on Disk.",
        "other": "There are files on Disk.",
        "default": "There are files on Disk."
    }
});

The getText() method returns the translated string for a given key.

translation.getText("hello"); // "Hello World!"

There are also methods for plural rules. The getPluralRuleText() method returns the translated string for a given key and a given number.

translation.getPluralRuleText("text6", 0); // "There are no files on Disk."
translation.getPluralRuleText("text6", 1); // "There is one file on Disk."
translation.getPluralRuleText("text6", 2); // "There are files on Disk."

Document Translation

First, you have to create a new script element with the data-monster-role="translations" and the type="application/json" attribute. The content of the element must be a JSON object.

<script type="application/json" data-monster-role="translations">
    {
        "key1": "translation1",
        "key2": {
            "other": "translation2"
        }
    }
</script> 

Then you have to assign the translations to the document. This can be done with the assignTranslationsToDocument() method. This static method returns a promise. Than you can use the getDocumentTranslations() method to get the translations. Finally, you can use the getText() method to get the translated string.

import { Embed } from "@schukai/monster/source/i18n/providers/embed.mjs";
import { getDocumentTranslations } from "@schukai/monster/source/i18n/translations.mjs";

Embed.assignTranslationsToElement().then(() => {

    const translations = getDocumentTranslations();

    translations.getText('no-key','with-default')
    // ↦ with-default

    translations.getText('key1')
    // ↦ translation1

}).catch((e) => {
// ...
})