# 应用本地化

中间件 i18n 为 [Macaron 实例](https://go-macaron.com/core_concepts#macaron-shi-li) 提供了国际化和本地化应用的功能。

* [GitHub](https://github.com/go-macaron/i18n)
* [API 文档](https://gowalker.org/github.com/go-macaron/i18n)

## 下载安装

```bash
go get github.com/go-macaron/i18n
```

## 使用示例

```go
// 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
    })

    // 在处理器中使用
    m.Get("/trans", func(ctx *macaron.Context) string {
        return ctx.Tr("hello %s", "world")
    })

    m.Run()
}
```

```markup
<!-- templates/hello.tmpl -->
<h2>{{i18n.Tr "hello %s" "world"}}!</h2>
```

### Pongo2 模板引擎

在 [pongo2](https://github.com/flosch/pongo2) 模板引擎中使用 i18n 中间件：

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

## 自定义选项

该服务允许接受一个参数来进行自定义选项（[`i18n.Options`](https://gowalker.org/github.com/go-macaron/i18n#Options)）：

```go
// ...
m.Use(i18n.I18n(i18n.Options{
    // 存放本地化文件的目录，默认为 "conf/locale"
    Directory:    "conf/locale",
    // 支持的语言，顺序是有意义的
    Langs:        []string{"en-US", "zh-CN"},
    // 语言的本地化名称
    Names:        []string{"English", "简体中文"},
    // 本地化文件命名风格，默认为 "locale_%s.ini"
    Format:        "locale_%s.ini",
    // 指示当前语言的 URL 参数名，默认为 "lang"
    Parameter:    "lang",
    // 当通过 URL 参数指定语言时是否重定向，默认为 false
    Redirect:    false,
    // 存放在模板中的本地化对象变量名称，默认为 "i18n"
    TmplName:    "i18n",
}))
// ...
```

## 加载本地化文件

默认情况下，本地化文件应当存放在相对当前目录的 `conf/locale` 文件夹下：

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

## 其它说明

* 请查看 [unknwon/i18n](https://github.com/Unknwon/i18n) 包来了解本地化使用规范。
* 您可以将 [Peach Docs](https://github.com/peachdocs/peach) 作为学习案例。
