tr
Easy drop-in i18n solution for Go applications.
I was looking for a real easy way to provide i18n support for my Telegram
bot, for which the data is pretty much a set of 20 different text messages.
I couldn't find a single solution that would utilize the file system.
Here's how tr
works:
-
You have to create a locales directory, e.g. $ tree lang
:
lang
├── en
│ ├── hello.txt
│ └── inner
│ └── text.txt
├── fr
│ ├── hello.txt
│ └── inner
│ └── text.txt
└── ru
├── hello.txt
└── inner
└── text.html
6 directories, 6 files
Your files could be of any extension, it doesn't really matter,
since tr
ignores extensions anyway.
-
Init tr
properly in your program:
package main
import (
"fmt"
"os"
"github.com/tucnak/tr"
)
func init() {
// tr.Init(localesDirectory, defaultLocale)
engine, err := tr.Init("lang", "en")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
-
Use simple syntax for i18n:
// Inline syntax:
fmt.Println("In English:", engine.Lang("en").Tr("hello"))
fmt.Println("In French:", engine.Lang("fr").Tr("hello"))
fmt.Println("In Russian:", engine.Lang("ru").Tr("hello"))
// Shadowing
engine := engine.Lang("fr")
fmt.Println(engine.Tr("inner/text"))
Pass an optional third true
argument to tr.Init()
if you wish
to trim all \n
s from the end of the string returned.