Changes

→‎Mod APIs: add translation API
Line 409: Line 409:  
// get manifest info for all loaded mods
 
// get manifest info for all loaded mods
 
foreach(IManifest manifest in this.Helper.ModRegistry.GetAll()) { … }
 
foreach(IManifest manifest in this.Helper.ModRegistry.GetAll()) { … }
 +
</source>
 +
 +
===Translation===
 +
'''This is a draft API in the upcoming SMAPI 1.14.'''
 +
 +
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 <tt>pt-BR.json</tt>, SMAPI will check <tt>pt.json</tt> and <tt>default.json</tt>). Translations can be a simple string, or they can include tokens to inject values into the translation.
 +
 +
====File structure====
 +
SMAPI reads translations from internationalisation (i18n) files in a structure like this:
 +
<pre>
 +
YourMod/
 +
  i18n/
 +
      default.json
 +
      es.json
 +
      pt.json
 +
  manifest.json
 +
  YourMod.dll
 +
</pre>
 +
 +
The <tt>default.json</tt> file should contain a flat key→value lookup with your default text. Each key can contain alphanumeric, underscore, hyphen, and dot characters. Feel free to add JavaScript comments to organise or document your translations. For example:
 +
<source lang="javascript">
 +
{
 +
    // example translations
 +
    "item-type.label": "Item type",
 +
    "item-type.fruit-tree": "{{fruitName}} tree",
 +
}
 +
</source>
 +
 +
You can then add translation files for each language you want to support (with a filename matching the locale code: <tt>de.json</tt> for German, <tt>en.json</tt> for English, <tt>es.json</tt> for Spanish, <tt>ja.json</tt> for Japanese, <tt>pt-BR.json</tt> for Brazilian Portuguese, or <tt>zh.json</tt> for Chinese). These should contain a copy of your <tt>default.json</tt> with the values translated.
 +
 +
====Reading translations====
 +
Once your i18n files are set up, you can read translations for the current locale:
 +
<source lang="c#">
 +
// read a simple translation
 +
string label = helper.Translate("item-type.label");
 +
 +
// read a translation which uses tokens
 +
string text = helper.Translate("item-type.fruit-tree").Tokens(new { fruitName = "apple" });
 +
</source>
 +
 +
The <tt>helper.Translate(…)</tt> 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:
 +
<source lang="c#">
 +
// use fluent chain
 +
string text = helper.Translate(key).Tokens(tokens).Assert();
 
</source>
 
</source>
    
[[Category:Modding]]
 
[[Category:Modding]]
translators
8,404

edits