forked from m1/go-localize
-
Notifications
You must be signed in to change notification settings - Fork 1
/
template.go
105 lines (86 loc) · 2.22 KB
/
template.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
97
98
99
100
101
102
103
104
105
package main
import (
"text/template"
)
var packageTemplate = template.Must(template.New("").Parse(`// Code generated by go-localize; DO NOT EDIT.
// This file was generated by robots at
// {{ .Timestamp }}
package {{ .Package }}
import (
"bytes"
"fmt"
"strings"
"text/template"
)
var localizations = map[string]string{
{{- range $key, $element := .Localizations }}
"{{ $key }}":{{ call $.LineUp $key }} "{{ $element }}",
{{- end }}
}
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
}
}
// If the str doesn't have any substitutions, no need to
// template.Execute.
if strings.Index(str, "}}") == -1 {
return str
}
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
}
`,
))