Ai
1 Star 1 Fork 0

bon-ami/eztools

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
i18n.go 1.58 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Tse 提交于 2023-01-12 15:42 +08:00 . thorough comments and camel names
package eztools
import (
"github.com/BurntSushi/toml"
"github.com/Xuanwo/go-locale"
"github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"
"golang.org/x/text/language/display"
)
var (
i18nBundle *i18n.Bundle
i18nLocalizer *i18n.Localizer
)
const i18nFmt = "toml"
// InitLanguages initialize resources for i18n
// 1/4
func InitLanguages() {
i18nBundle = i18n.NewBundle(language.English)
i18nBundle.RegisterUnmarshalFunc(i18nFmt, toml.Unmarshal)
}
// AddLanguage add a language resource
// 2*n/4
/* Example: ID = "translated string"
AddLanguage([]byte(`
StrFlw = "flow"
StrAll = "select all"
`), "en"))
*/
func AddLanguage(language, translations string) {
if i18nBundle == nil {
return
}
i18nBundle.MustParseMessageFileBytes([]byte(translations),
language+"."+i18nFmt)
}
// LoadLanguage load language of system
// 3/4
func LoadLanguage(lang string) (string, error) {
if len(lang) < 1 {
tag, err := locale.Detect()
if err != nil {
return "", err
}
lang = tag.String()
}
i18nLocalizer = i18n.NewLocalizer(i18nBundle, lang)
return lang, nil
}
// GetLanguageStr returns translated string by ID
// 4*n/4
func GetLanguageStr(id string) (string, error) {
if i18nLocalizer == nil {
return "", ErrOutOfBound
}
return i18nLocalizer.Localize(&i18n.LocalizeConfig{MessageID: id})
}
// ListLanguages loops all translated languages
// Parameters: name is like "English", id is like "en"
func ListLanguages(fun func(name, id string)) {
if i18nBundle == nil {
return
}
for _, tag := range i18nBundle.LanguageTags() {
fun(display.Self.Name(tag), tag.String())
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/bon-ami/eztools.git
git@gitee.com:bon-ami/eztools.git
bon-ami
eztools
eztools
v5.0.2

搜索帮助