Modding:Modder Guide/APIs/Translation

From Stardew Valley Wiki
< Modding:Modder Guide‎ | APIs
Revision as of 01:38, 28 May 2018 by Pathoschild (talk | contribs) (move content from Modding:Modder Guide/APIs (only author is Pathoschild))
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Creating SMAPI mods SMAPI mascot.png


Modding:Index

Translation

The translation API lets you translate your mod into the player's current language, accounting for locale fallback automatically (e.g. if a translation isn't available in pt-BR.json, SMAPI will check pt.json and default.json). Translations can be a simple string, or they can include tokens to inject values into the translation.

File structure
SMAPI reads translations from JSON files in a structure like this:
YourMod/
   i18n/
      default.json
      es.json
      pt.json
   manifest.json
   YourMod.dll

The default.json file should contain a flat key→value lookup with your default text. Each key is case-insensitive, and can contain alphanumeric, underscore, hyphen, and dot characters. Feel free to add JavaScript comments to organise or document your translations. For example:

{
    // example translations
    "item-type.label": "Item type",
    "item-type.fruit-tree": "{{fruitName}} tree",
}

You can then add translation files for each language you want to support, by copying the default.json file and translating its values. Each translation file should have one of these file names:

Language File name
Chinese zh.json
German de.json
Japanese ja.json
Portuguese pt.json
Russian ru.json
Spanish es.json
Reading translations
Once your i18n files are set up, you can read translations for the current locale:
// read a simple translation
string label = helper.Translation.Get("item-type.label");

// read a translation which uses tokens (accepts an anonymous object, dictionary, or model)
string text = helper.Translation.Get("item-type.fruit-tree", new { fruitName = "apple" });

The helper.Translate(…) method returns a fluent interface — you can keep calling methods on its return value to customise the translation. (See IntelliSense for a description of the available methods.) To get the text, simply assign it to a string:

// use fluent chain
string text = helper.Translate(key).Tokens(tokens).Tokens(moreTokens).Assert();

If your code has a lot of translation calls, you can make it less verbose by aliasing the translation helper:

var i18n = helper.Translation;

i18n.Get("item-type.fruit-tree", new { fruitName = i18n.Get("apple") });
Tips for translators
  • Save i18n files with UTF-8 encoding to avoid broken symbols in-game.
  • Type reload_i18n into the SMAPI console and hit enter to reload translations without exiting the game. (If a mod internally cached a translation, it may not be updated.)