2022-03-16 13:32:48 -04:00
|
|
|
package i18n
|
|
|
|
|
|
|
|
import (
|
|
|
|
"embed"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
2022-03-16 16:58:42 -04:00
|
|
|
"strings"
|
2022-03-16 13:32:48 -04:00
|
|
|
|
|
|
|
"github.com/documize/community/core/asset"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
2022-03-16 16:58:42 -04:00
|
|
|
const (
|
|
|
|
DefaultLocale = "en-US"
|
|
|
|
)
|
|
|
|
|
2022-03-16 13:32:48 -04:00
|
|
|
var localeMap map[string]map[string]string
|
|
|
|
|
|
|
|
// SupportedLocales returns array of locales.
|
|
|
|
func SupportedLocales() (locales []string) {
|
|
|
|
locales = append(locales, "en-US")
|
2022-04-08 11:59:08 -04:00
|
|
|
locales = append(locales, "de-DE")
|
2022-07-09 08:50:35 +08:00
|
|
|
locales = append(locales, "zh-CN")
|
2022-07-12 22:14:26 -03:00
|
|
|
locales = append(locales, "pt-BR")
|
2022-03-16 13:32:48 -04:00
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Intialize will load language files
|
|
|
|
func Initialize(e embed.FS) (err error) {
|
|
|
|
localeMap = make(map[string]map[string]string)
|
|
|
|
|
|
|
|
locales := SupportedLocales()
|
|
|
|
|
|
|
|
for i := range locales {
|
|
|
|
content, _, err := asset.FetchStatic(e, "i18n/"+locales[i]+".json")
|
|
|
|
if err != nil {
|
|
|
|
err = errors.Wrap(err, fmt.Sprintf("missing locale %s", locales[i]))
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
var payload interface{}
|
|
|
|
json.Unmarshal([]byte(content), &payload)
|
|
|
|
m := payload.(map[string]interface{})
|
|
|
|
|
|
|
|
translations := make(map[string]string)
|
|
|
|
|
|
|
|
for j := range m {
|
|
|
|
translations[j] = m[j].(string)
|
|
|
|
}
|
|
|
|
|
|
|
|
localeMap[locales[i]] = translations
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Localize will returns string value for given key using specified locale).
|
|
|
|
// e.g. locale = "en-US", key = "admin_billing"
|
2022-03-16 16:58:42 -04:00
|
|
|
//
|
|
|
|
// Replacements are for replacing string placeholders ({1} {2} {3}) with
|
|
|
|
// replacement text.
|
2022-04-08 11:59:08 -04:00
|
|
|
// e.g. "This is {1} example" --> replacements[0] will replace {1}
|
2022-03-16 16:58:42 -04:00
|
|
|
func Localize(locale string, key string, replacements ...string) (s string) {
|
2022-03-16 13:32:48 -04:00
|
|
|
l, ok := localeMap[locale]
|
|
|
|
if !ok {
|
|
|
|
// fallback
|
2022-03-16 16:58:42 -04:00
|
|
|
l = localeMap[DefaultLocale]
|
2022-03-16 13:32:48 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
s, ok = l[key]
|
|
|
|
if !ok {
|
|
|
|
// missing translation key is echo'ed back
|
|
|
|
s = fmt.Sprintf("!! %s !!", key)
|
|
|
|
}
|
|
|
|
|
2022-03-16 16:58:42 -04:00
|
|
|
// placeholders are one-based: {1} {2} {3}
|
|
|
|
// replacements array is zero-based hence the +1 below
|
|
|
|
if len(replacements) > 0 {
|
|
|
|
for i := range replacements {
|
|
|
|
s = strings.Replace(s, fmt.Sprintf("{%d}", i+1), replacements[i], 1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-16 13:32:48 -04:00
|
|
|
return
|
|
|
|
}
|