diff options
author | wxiaoguang <wxiaoguang@gmail.com> | 2022-01-02 11:33:57 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-01-02 04:33:57 +0100 |
commit | e61b390d545919244141b699b28e3fbc42adc66f (patch) | |
tree | de17418a260234e1043a6d3a130c2b4a8c27640a /modules/translation/translation.go | |
parent | 88da7a7174f9c1568cc2d8d084d6b05a8d268690 (diff) | |
download | gitea-e61b390d545919244141b699b28e3fbc42adc66f.tar.gz gitea-e61b390d545919244141b699b28e3fbc42adc66f.zip |
Unify and simplify TrN for i18n (#18141)
Refer: https://github.com/go-gitea/gitea/pull/18135#issuecomment-1003246099
Now we have a unique and simple `TrN`, and make the fix of PR #18135 also use the better `TrN` logic.
Diffstat (limited to 'modules/translation/translation.go')
-rw-r--r-- | modules/translation/translation.go | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/modules/translation/translation.go b/modules/translation/translation.go index 77cc9ac7f5..af1e5d25df 100644 --- a/modules/translation/translation.go +++ b/modules/translation/translation.go @@ -17,6 +17,7 @@ import ( type Locale interface { Language() string Tr(string, ...interface{}) string + TrN(cnt interface{}, key1, keyN string, args ...interface{}) string } // LangType represents a lang type @@ -99,3 +100,67 @@ func (l *locale) Language() string { func (l *locale) Tr(format string, args ...interface{}) string { return i18n.Tr(l.Lang, format, args...) } + +// Language specific rules for translating plural texts +var trNLangRules = map[string]func(int64) int{ + // the default rule is "en-US" if a language isn't listed here + "en-US": func(cnt int64) int { + if cnt == 1 { + return 0 + } + return 1 + }, + "lv-LV": func(cnt int64) int { + if cnt%10 == 1 && cnt%100 != 11 { + return 0 + } + return 1 + }, + "ru-RU": func(cnt int64) int { + if cnt%10 == 1 && cnt%100 != 11 { + return 0 + } + return 1 + }, + "zh-CN": func(cnt int64) int { + return 0 + }, + "zh-HK": func(cnt int64) int { + return 0 + }, + "zh-TW": func(cnt int64) int { + return 0 + }, + "fr-FR": func(cnt int64) int { + if cnt > -2 && cnt < 2 { + return 0 + } + return 1 + }, +} + +// TrN returns translated message for plural text translation +func (l *locale) TrN(cnt interface{}, key1, keyN string, args ...interface{}) string { + var c int64 + if t, ok := cnt.(int); ok { + c = int64(t) + } else if t, ok := cnt.(int16); ok { + c = int64(t) + } else if t, ok := cnt.(int32); ok { + c = int64(t) + } else if t, ok := cnt.(int64); ok { + c = t + } else { + return l.Tr(keyN, args...) + } + + ruleFunc, ok := trNLangRules[l.Lang] + if !ok { + ruleFunc = trNLangRules["en-US"] + } + + if ruleFunc(c) == 0 { + return l.Tr(key1, args...) + } + return l.Tr(keyN, args...) +} |