2 Translation
Kristian Knarvik edited this page 2023-01-25 16:40:38 +01:00

KnarLib has a general-purpose translator which is simple, but powerful. It automatically allows any translatable strings to be overridden by the server owner, which also allows anyone to add a custom language.

The basic translation format is as follows, and should be placed in the resource folder in strings.yml:

languageCode:
  TRANSLATABLE_STRING_1: "The text to be displayed as the translation"
  TRANSLATABLE_STRING_2: "The different text to be displayed as the translation"

Example:

en:
  PLUGIN_RELOADED: "Successfully reloaded"
  PERMISSION_DENIED: "You don't have the necessary permission"
no:
  PLUGIN_RELOADED: "Lastet inn på nytt"
  PERMISSION_DENIED: "Du har ikke tilgang"

Language codes can use any format you want. So you could use "en", "en-US", "English" or whatever else. Just make sure to be consistent to avoid confusing your users. If a strings.yml file is found in the plugin folder, any translations in that will take precedence over the values set in your plugin, which allows full customization by the end-user. Color and formatting codes in translated messages will be automatically converted into formatted text. This behavior can be tweaked using translator.setColorConversion.

To create your translatable messages, create a an enum extending TranslatableMessage like so:

public enum MyTranslatableMessage implements TranslatableMessage {
    TRANSLATABLE_STRING_1,
    TRANSLATABLE_STRING_2
    
    //This is necessary for the translator to get available messages
    @Override
    public TranslatableMessage[] getAllMessages() {
        return MyTranslatableMessage.values();
    }
}

If you've created your class, and strings.yml file, you can start using your translator. First, make a new translator. Then, register one message for each class you've made that extends TranslatableMessage using translator.registerMessageCategory. When that's done, use translator.loadLanguages to load your translations:

Translator translator = new Translator();
translator.registerMessageCategory(MyTranslatableMessage.TRANSLATABLE_STRING_1);
//The data folder for your plugin | The default language, if translations are missing | The selected language
translator.loadLanguages(this.getDataFolder(), "en", "no");

Now, your translator is ready for use. To get a translation, simply run translator.getTranslatedMessage on one of your messages:

String translation = translator.getTranslatedMessage(MyTranslatableMessage.TRANSLATABLE_STRING_1);