Very basic Golang library for i18n.
The original project was by @kortemy, and uses JSON. A fork by jdkeke142 changed the input to TOML. This fork abstracts the file system away, allowing the use of (for example) embedded assets, or assets that don't live on the local disk. It was put together around broccoli, with which it's been tested.
- Storing messages in TOML files.
- Support for nested declarations.
- Detecting language based on Request headers.
- Very simple to use.
-
Import Lingo into your project
import "github.com/xxxserxxx/lingo"
-
Create a dir to store translations, and write them in TOML files named [locale].toml. For example:
en_US.toml sr_RS.toml de.toml ...
You can write nested TOML too.
title = "CutleryPlus" subtitle = "Knives that put cut in cutlery." [menu] home = "Home" [menu.products] self = "Products" forks = "Forks" knives = "Knives" spoons = "Spoons"
-
Initialize a Lingo like this:
l := lingo.New("default_locale", "path/to/translations/dir", nil)
This is where you would pass in a
lingo.FileSystem
if you want lingo to read from something other than the disk. Passing innil
is the same as calling:l := lingo.New("default_locale", "path/to/translations/dir", lingo.OSFS())
-
Get bundle for specific locale via either
string
:t1 := l.TranslationsForLocale("en_US") t2 := l.TranslationsForLocale("de_DE")
This way Lingo will return the bundle for specific locale, or default if given is not found. Alternatively (or primarily), you can get it with
*http.Request
:t := l.TranslationsForRequest(req)
This way Lingo finds best suited locale via
Accept-Language
header, or if there is no match, returns default.Accept-Language
header is set by the browser, so basically it will serve the language the user has set to his browser. -
Once you get T instance just fire away!
r1 := t1.Value("main.subtitle") // "Knives that put cut in cutlery." r1 := t2.Value("main.subtitle") // "Messer, die legte in Besteck geschnitten." r3 := t1.Value("menu.products.self") // "Products" r5 := t1.Value("error.404", req.URL.Path) // "Page index.html not found!"
-
Lingo will return the default locale if it can't find a requested locale.
-
Lingo will return the default locale's text if it can't find a translation for the key in the requested locale.
-
Lingo will return the requested key if it can't find either the requested or the default text.
-
Text values can have positional tags, e.g.
{0}
,{1}
. These will be replaced by any varargs supplied toValue
. E.g.:thing="Hey there, {1}, how is {0}?"
and
res := t1.Value("thing", "your dog", "person")
will produce
Hey there, person, how is your dog
-
Locales must match the file names. E.g.,
en_US
must be in a file calleden_US.toml
, noten_us.toml
. -
Files in the translation directory that do not end in
.toml
are ignored.
This was forked to support another project; I'll accept PRs and will fix bugs, but am unlikely to add features.