-
Notifications
You must be signed in to change notification settings - Fork 0
/
localize.go
98 lines (79 loc) · 2 KB
/
localize.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
package localize
import (
"github.com/leonelquinteros/gotext"
"github.com/ugent-library/biblio-backoffice/render/form"
"github.com/ugent-library/biblio-backoffice/validation"
"github.com/ugent-library/biblio-backoffice/vocabularies"
"golang.org/x/text/language"
"golang.org/x/text/language/display"
)
// TODO hardcoded to English for now
var languageNamer = display.Languages(language.MustParse("en"))
func ValidationErrors(loc *gotext.Locale, errs validation.Errors) []string {
msgs := make([]string, len(errs))
for i, e := range errs {
msgs[i] = loc.Get("validation." + e.Code)
}
return msgs
}
func ValidationErrorAt(loc *gotext.Locale, errs validation.Errors, ptr string) string {
err := errs.At(ptr)
if err == nil {
return ""
}
return loc.Get("validation." + err.Code)
}
// TODO memoize this
func LanguageName(code string) string {
tag := language.Make(code)
if name := languageNamer.Name(tag); name != "" {
return name
}
return code
}
func LanguageNames(codes []string) []string {
names := make([]string, len(codes))
for i, code := range codes {
names[i] = LanguageName(code)
}
return names
}
func LanguageSelectOptions() []form.SelectOption {
vals, ok := vocabularies.Map["language_codes"]
if !ok {
return nil
}
opts := make([]form.SelectOption, len(vals))
for i, v := range vals {
opts[i] = form.SelectOption{
Value: v,
Label: LanguageName(v),
}
}
return opts
}
func VocabularyTerms(loc *gotext.Locale, key string) map[string]string {
vals, ok := vocabularies.Map[key]
if !ok {
return nil
}
translatedTerms := make(map[string]string, len(vals))
for _, v := range vals {
translatedTerms[v] = loc.Get(key + "." + v)
}
return translatedTerms
}
func VocabularySelectOptions(loc *gotext.Locale, key string) []form.SelectOption {
vals, ok := vocabularies.Map[key]
if !ok {
return nil
}
opts := make([]form.SelectOption, len(vals))
for i, v := range vals {
opts[i] = form.SelectOption{
Value: v,
Label: loc.Get(key + "." + v),
}
}
return opts
}