| 1 | package i18n |
| 2 | |
| 3 | import "fmt" |
| 4 | |
| 5 | // Empty is a string which translates into the empty string "". |
| 6 | // Needed because empty strings in Dict denote missing translations. |
| 7 | const Empty = "\xff" |
| 8 | |
| 9 | // Dict describes a dictionary, it holds translations of a phrase or sentence. |
| 10 | // |
| 11 | // Keyed composite literals should be used always to create instances, |
| 12 | // where keys (indices) are the locales. |
| 13 | // |
| 14 | // Empty string elements "" denote missing translations for the locale denoted |
| 15 | // by the index. If you want the translation to be the empty string, you must |
| 16 | // use the Empty constant as the value. |
| 17 | type Dict []string |
| 18 | |
| 19 | // Get returns the translation for the given locale. |
| 20 | // If no translation exists for the given locale, translation for the default |
| 21 | // locale (which is 0) is returned. |
| 22 | // |
| 23 | // If arguments are provided, the translation is treated as a format string, |
| 24 | // and fmt.Sprintf() is called to generate the result. |
| 25 | // |
| 26 | // If the translation is the Empty constant, the empty string is returned |
| 27 | // without calling fmt.Sprintf() even if arguments are provided. |
| 28 | func (d Dict) Get(locale int, a ...interface{}) string { |
| 29 | var format string |
| 30 | if locale < len(d) { |
| 31 | format = d[locale] |
| 32 | } |
| 33 | |
| 34 | if format == "" { |
| 35 | format = d[0] |
| 36 | } |
| 37 | |
| 38 | if format == Empty { |
| 39 | return "" |
| 40 | } |
| 41 | if a == nil { |
| 42 | return format |
| 43 | } |
| 44 | return fmt.Sprintf(format, a...) |
| 45 | } |
| 46 | |
| 47 | // Translator is the type of the Dict.Get method. |
| 48 | type Translator func(locale int, a ...interface{}) string |