Localization

Middleware i18n provides app Internationalization and Localization for Macaron Instances.

Installation

go get github.com/go-macaron/i18n

Usage

// main.go
import (
    "github.com/go-macaron/i18n"
    "gopkg.in/macaron.v1"
)

func main() {
      m := macaron.Classic()
      m.Use(i18n.I18n(i18n.Options{
        Langs:    []string{"en-US", "zh-CN"},
        Names:    []string{"English", "简体中文"},
    }))

    m.Get("/", func(locale i18n.Locale) string {
        return "current language is" + locale.Lang
    })

    // Use in handler.
    m.Get("/trans", func(ctx *macaron.Context) string {
        return ctx.Tr("hello %s", "world")
    })

    m.Run()
}
<!-- templates/hello.tmpl -->
<h2>{{.i18n.Tr "hello %s" "world"}}!</h2>

Pongo2

To use i18n feature in pongo2 with middleware pongo2:

<!-- templates/hello.tmpl -->
<h2>{{Tr(Lang,"hello %s","world")}}!</h2>

Options

i18n.I18n comes with a variety of configuration options(i18n.Options):

// ...
m.Use(i18n.I18n(i18n.Options{
    // Directory to load locale files. Default is "conf/locale".
    Directory:    "conf/locale",
    // Languages that will be supported, order is meaningful.
    Langs:        []string{"en-US", "zh-CN"},
    // Human friendly names corresponding to Langs list.
    Names:        []string{"English", "简体中文"},
    // Locale file naming style. Default is "locale_%s.ini".
    Format:        "locale_%s.ini",
    // Name of language parameter name in URL. Default is "lang".
    Parameter:    "lang",
    // Redirect when user uses get parameter to specify language. Default is false.
    Redirect:    false,
    // Name that maps into template variable. Default is "i18n".
    TmplName:    "i18n",
}))
// ...

Loading Locale Files

By default, locale files should be put in conf/locale:

conf/
  |
  |__ locale/
        |
        |__ locale_en-US.ini
        |
        |__ locale_zh-CN.ini

Others

Last updated