mirror of
https://github.com/documize/community.git
synced 2025-07-19 05:09:42 +02:00
i18n server-side strings
This commit is contained in:
parent
f4a1350a41
commit
df534f72fa
11 changed files with 59 additions and 131 deletions
|
@ -4,12 +4,17 @@ import (
|
|||
"embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/documize/community/core/asset"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultLocale = "en-US"
|
||||
)
|
||||
|
||||
var localeMap map[string]map[string]string
|
||||
|
||||
// type translation struct {
|
||||
|
@ -57,11 +62,15 @@ func Initialize(e embed.FS) (err error) {
|
|||
|
||||
// Localize will returns string value for given key using specified locale).
|
||||
// e.g. locale = "en-US", key = "admin_billing"
|
||||
func Localize(locale, key string) (s string) {
|
||||
//
|
||||
// Replacements are for replacing string placeholders ({1} {2} {3}) with
|
||||
// replacement text.
|
||||
// e.g. "This is {1} example" where replacements[0] will replace {1}
|
||||
func Localize(locale string, key string, replacements ...string) (s string) {
|
||||
l, ok := localeMap[locale]
|
||||
if !ok {
|
||||
// fallback
|
||||
l = localeMap["en-US"]
|
||||
l = localeMap[DefaultLocale]
|
||||
}
|
||||
|
||||
s, ok = l[key]
|
||||
|
@ -70,5 +79,13 @@ func Localize(locale, key string) (s string) {
|
|||
s = fmt.Sprintf("!! %s !!", key)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue