i18n #
Description
i18n loads translations from a directory and looks them up by language and key.
Translation files
Both formats are read from the same directory, and may be mixed.
.tr
The primary format. Each entry is a key line, the text below it, and a ----- separator:
msg_hello
Hello
-----
goods
goods|item|items
The file name is the language: translations/en.tr defines the en translations.
.json
Useful when translations are produced by an external localization tool, or when they are large enough to be worth splitting per feature.
translations/en.json defines the en translations, exactly like en.tr does:
{
'msg_hello': 'Hello',
'menu': {
'file': 'File',
'edit': { 'undo': 'Undo' }
}
}
Nested objects are flattened with ., so the above defines msg_hello, menu.file and menu.edit.undo.
A file inside a language subdirectory is namespaced by its own name, so translations can be split per feature. translations/zh/dashboard.json defines zh keys under dashboard.:
{ 'title': 'Dashboard', 'widgets': { 'clock': 'Clock' } }
gives dashboard.title and dashboard.widgets.clock.
Non-string scalar values use their JSON representation, so 42, true, and null are loaded as "42", "true", and "null". Arrays are ignored.
When the same key is defined by both formats, the .tr value wins.
Usage
import i18n
println(i18n.tr('en', 'msg_hello'))
println(i18n.tr_plural('en', 'goods', 2))
tr and tr_plural read from the translations directory. Use load_tr_map_from_dir with tr_from_map / tr_plural_from_map to read from another directory.
Constants #
const default_translations_dir = 'translations'
fn load_tr_map #
fn load_tr_map() map[string]map[string]string
load_tr_map loads all .tr files from the default translations directory.
fn load_tr_map_from_dir #
fn load_tr_map_from_dir(dir string) map[string]map[string]string
load_tr_map_from_dir loads all .tr and .json files from dir into a lang -> key -> text map. A .tr entry wins when the same key is defined by both formats, since .tr is the primary format.
fn tr #
fn tr(lang string, key string) string
tr returns the translation for key from the default translations directory.
fn tr_from_map #
fn tr_from_map(translations map[string]map[string]string, lang string, key string) string
tr_from_map returns the translation for key from translations.
fn tr_plural #
fn tr_plural(lang string, key string, amount int) string
tr_plural returns the pluralized translation for key from the default translations directory.
fn tr_plural_from_map #
fn tr_plural_from_map(translations map[string]map[string]string, lang string, key string, amount int) string
tr_plural_from_map returns the pluralized translation for key from translations.