forked from m1/go-localize
-
Notifications
You must be signed in to change notification settings - Fork 0
/
localizations.go
96 lines (81 loc) · 2.41 KB
/
localizations.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Code generated by go-localize; DO NOT EDIT.
// This file was generated by robots at
// 2019-12-19 20:40:24.756426604 +0000 GMT m=+0.000940957
package localizations
import (
"bytes"
"fmt"
"text/template"
)
var localizations = map[string]string{
"en.messages.hello": "hello",
"en.messages.hello_firstname_lastname": "Hello {{.firstname}} {{.lastname}}",
"en.messages.hello_my_name_is": "Hello my name is {{.name}}",
"en.messages.how_are_you": "How are you?",
"en.messages.whats_your_name": "What's your name?",
"es.customer.messages.hello": "hello customer!",
"es.messages.hello": "Hola",
"es.messages.hello_my_name_is": "Hola, mi nombre es {{.name}}",
"es.messages.how_are_you": "¿Cómo estás?",
"es.messages.whats_your_name": "¿Cuál es tu nombre?",
}
type Replacements map[string]interface{}
type Localizer struct {
Locale string
FallbackLocale string
Localizations map[string]string
}
func New(locale string, fallbackLocale string) *Localizer {
t := &Localizer{Locale: locale, FallbackLocale: fallbackLocale}
t.Localizations = localizations
return t
}
func (t Localizer) SetLocales(locale, fallback string) Localizer {
t.Locale = locale
t.FallbackLocale = fallback
return t
}
func (t Localizer) SetLocale(locale string) Localizer {
t.Locale = locale
return t
}
func (t Localizer) SetFallbackLocale(fallback string) Localizer {
t.FallbackLocale = fallback
return t
}
func (t Localizer) GetWithLocale(locale, key string, replacements ...*Replacements) string {
str, ok := t.Localizations[t.getLocalizationKey(locale, key)]
if !ok {
str, ok = t.Localizations[t.getLocalizationKey(t.FallbackLocale, key)]
if !ok {
return key
}
}
return t.replace(str, replacements...)
}
func (t Localizer) Get(key string, replacements ...*Replacements) string {
str := t.GetWithLocale(t.Locale, key, replacements...)
return str
}
func (t Localizer) getLocalizationKey(locale string, key string) string {
return fmt.Sprintf("%v.%v", locale, key)
}
func (t Localizer) replace(str string, replacements ...*Replacements) string {
b := &bytes.Buffer{}
tmpl, err := template.New("").Parse(str)
if err != nil {
return str
}
replacementsMerge := Replacements{}
for _, replacement := range replacements {
for k, v := range *replacement {
replacementsMerge[k] = v
}
}
err = template.Must(tmpl, err).Execute(b, replacementsMerge)
if err != nil {
return str
}
buff := b.String()
return buff
}