Line 77: |
Line 77: |
| | | |
| ==Reading translations== | | ==Reading translations== |
| + | ===Built-in API=== |
| Once your i18n files are set up, you can read translations for the current locale: | | Once your i18n files are set up, you can read translations for the current locale: |
| <source lang="c#"> | | <source lang="c#"> |
Line 86: |
Line 87: |
| </source> | | </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: | + | 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, just assign it to a string: |
| <source lang="c#"> | | <source lang="c#"> |
| // use fluent chain | | // use fluent chain |
− | string text = helper.Translate(key).Tokens(tokens).Tokens(moreTokens); | + | string text = helper.Translation.Get(key).Tokens(tokens).Tokens(moreTokens).Default("missing translation?"); |
| </source> | | </source> |
| | | |
− | If your code has a lot of translation calls, you can make it less verbose by aliasing the translation helper:
| + | ===Strongly-typed API=== |
| + | The built-in API doesn't have build-time validation. For example, if you set a <code>fruitName</code> argument but the translation actually uses <code><nowiki>{{fruit}}</nowiki></code>, you won't know until you test each translation in-game and see the broken message. That's fine for most mods, but can be an issue with larger mods that have hundreds of translations across many different UI flows. |
| + | |
| + | The optional [https://github.com/Pathoschild/SMAPI-ModTranslationClassBuilder#readme SMAPI mod translation class builder] package lets you generate a strongly-typed class to read translations like this instead: |
| <source lang="c#"> | | <source lang="c#"> |
− | var i18n = helper.Translation;
| + | string label = I18n.ItemType_Label(); |
| + | string text = I18n.ItemType_FruitTree(fruitName: "apple"); |
| + | </source> |
| | | |
− | i18n.Get("item-type.fruit-tree", new { fruitName = i18n.Get("apple") });
| + | If a translation breaks, you'll know immediately since it won't compile. |
− | </source>
| |