Skip to content

Commit 59d14ea

Browse files
committed
Add translation example
1 parent bae7f6d commit 59d14ea

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

_examples/translations/main.go

+12-5
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@ package main
22

33
import (
44
"fmt"
5+
"github.com/go-playground/locales/zh"
56

67
"github.com/go-playground/locales/en"
78
ut "github.com/go-playground/universal-translator"
89
"github.com/go-playground/validator/v10"
910
en_translations "github.com/go-playground/validator/v10/translations/en"
11+
zh_translations "github.com/go-playground/validator/v10/translations/zh"
1012
)
1113

1214
// User contains user information
@@ -38,15 +40,20 @@ func main() {
3840
// NOTE: omitting allot of error checking for brevity
3941

4042
en := en.New()
41-
uni = ut.New(en, en)
43+
uni = ut.New(en, en, zh.New())
4244

43-
// this is usually know or extracted from http 'Accept-Language' header
45+
validate = validator.New()
46+
// The supported locales need to be predefined.
47+
enTrans, _ := uni.GetTranslator("en")
48+
en_translations.RegisterDefaultTranslations(validate, enTrans)
49+
zhTrans, _ := uni.GetTranslator("zh")
50+
zh_translations.RegisterDefaultTranslations(validate, zhTrans)
51+
52+
// this is usually know or extracted from http 'Accept-Language' header e.g.
53+
// Example values to pass: zh, en
4454
// also see uni.FindTranslator(...)
4555
trans, _ := uni.GetTranslator("en")
4656

47-
validate = validator.New()
48-
en_translations.RegisterDefaultTranslations(validate, trans)
49-
5057
translateAll(trans)
5158
translateIndividual(trans)
5259
translateOverride(trans) // yep you can specify your own in whatever locale you want!

0 commit comments

Comments
 (0)