Pavel Oborin
Dec 7, 2018 · 5 min read
Photo by rawpixel on Unsplash
message.SetString(language.Russian, “toxic”, “токсичный”)
message.SetString(language.Japanese, “toxic”, “毒性”)
message.NewPrinter(language.Russian).Println(“toxic”)
message.NewPrinter(language.Japanese).Println(“toxic”)
//Results:
//токсичный
//毒性
type dictionary struct {
Data map[string]string
}
func (d *dictionary) Lookup(key string) (data string, ok bool) {
if value, ok := d.Data[key]; ok {
return “\x02” + value, true
}
return “”, false
}
func parseYAMLDict() (map[string]catalog.Dictionary, error) {
dir := “./translations”
files, err := ioutil.ReadDir(dir)
if err != nil {
return nil, err
}
translations := map[string]catalog.Dictionary{} for _, f := range files {
yamlFile, err := ioutil.ReadFile(dir + “/” + f.Name())
if err != nil {
return nil, err
}
data := map[string]string{}
err = yaml.Unmarshal(yamlFile, &data)
if err != nil {
return nil, err
}
lang := strings.Split(f.Name(), “.”)[0] translations[lang] = &dictionary{Data: data}
}
return translations, nil
}
func init() {
dict, err := parseYAMLDict()
if err != nil {
panic(err)
}
cat, err := catalog.NewFromMap(dict)
if err != nil {
panic(err)
}
message.DefaultCatalog = cat
}
message.NewPrinter(language.Russian).Println(“label_name”)
template.New(tplName).Funcs(fmap).ParseFiles(tplName)
//Localization language
lang:=language.Russian
//Template name
tplName:=”./templates/hello.html”
//Variables in the template
data := &struct {
Name string
LastName string
}{Name: “Bill”, LastName: “Smith”}
fmap := template.FuncMap{
//Tag localization function
“translate”: message.NewPrinter(lang).Sprintf,
}
t, err := template.New(tplName).Funcs(fmap).ParseFiles(tplName)
if err != nil {
panic(err)
}
buf := bytes.NewBuffer([]byte{})
if err := t.Execute(buf, data); err != nil {
panic(err)
}
fmt.Println(buf.String())
<!DOCTYPE html>
<head>
<title>{{translate “hello_subject”}}</title>
</head>
<body>
{{translate “hello_msg” .Name .LastName}}
</body>
</html>
en.yml
hello_subject: Greeting mail
hello_msg: Hello, %s %s!
ru.yml
hello_subject: Welcome letter
hello_msg: Hello, %s %s!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade