-
Notifications
You must be signed in to change notification settings - Fork 2
/
messages.go
87 lines (69 loc) · 1.53 KB
/
messages.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
package localize
import (
"bytes"
"html/template"
"strings"
)
// A singleMessage contains a translation string or if used as a template a
// parsed template.Template.
type singleMessage struct {
S string
T *template.Template
}
func (s singleMessage) IsZero() bool {
return s.S == "" && s.T == nil
}
func (s singleMessage) Execute(data any) string {
if s.T == nil {
return s.S
}
var buf bytes.Buffer
s.T.Execute(&buf, data)
return buf.String()
}
func newSingleMessage(s string) singleMessage {
if strings.Contains(s, "{{") {
if t, err := template.New("").Parse(s); err == nil {
return singleMessage{T: t}
}
}
return singleMessage{S: s}
}
// pluralMessage contains the different options for plural translations.
type pluralMessage struct {
One singleMessage
Other singleMessage
// for Welsh only
Two singleMessage
Few singleMessage
Many singleMessage
}
type Messages struct {
Singles map[string]singleMessage
Plurals map[string]pluralMessage
}
func (m Messages) Find(key string) (singleMessage, bool) {
if msg, ok := m.Singles[key]; ok {
return singleMessage(msg), true
}
return singleMessage{}, false
}
func (m Messages) FindPlural(key string, count int) (singleMessage, bool) {
msg, ok := m.Plurals[key]
if !ok {
return singleMessage{}, false
}
if count == 1 {
return msg.One, true
}
if count == 2 && !msg.Two.IsZero() {
return msg.Two, true
}
if count == 3 && !msg.Few.IsZero() {
return msg.Few, true
}
if count == 6 && !msg.Many.IsZero() {
return msg.Many, true
}
return msg.Other, true
}