2.9 KiB
14.5 Multi-language support
In the chapter where we introduced internationalization and localization, we developed the go-i18n library. In this section, we will see how this library is integrated into the Beego framework, and how it enables our Beego applications to support both internationalization and localization.
I18n integration
Beego first sets some global variables:
Translation i18n.IL
Lang string // set the language pack, zh, en
LangPath string // set the language pack location
A multi-language initialization function is defined:
func InitLang(){
beego.Translation:=i18n.NewLocale()
beego.Translation.LoadPath(beego.LangPath)
beego.Translation.SetLocale(beego.Lang)
}
In order to facilitate multi-language calls in the template package directly, we designed three functions for handling multi-language responses:
beegoTplFuncMap["Trans"] = i18n.I18nT
beegoTplFuncMap["TransDate"] = i18n.I18nTimeDate
beegoTplFuncMap["TransMoney"] = i18n.I18nMoney
func I18nT(args ...interface{}) string {
ok := false
var s string
if len(args) == 1 {
s, ok = args[0].(string)
}
if !ok {
s = fmt.Sprint(args...)
}
return beego.Translation.Translate(s)
}
func I18nTimeDate(args ...interface{}) string {
ok := false
var s string
if len(args) == 1 {
s, ok = args[0].(string)
}
if !ok {
s = fmt.Sprint(args...)
}
return beego.Translation.Time(s)
}
func I18nMoney(args ...interface{}) string {
ok := false
var s string
if len(args) == 1 {
s, ok = args[0].(string)
}
if !ok {
s = fmt.Sprint(args...)
}
return beego.Translation.Money(s)
}
Use multi-language development
-
Set the location of language and language packs, then initialize the i18n objects:
beego.Lang = "zh" beego.LangPath = "views/lang" beego.InitLang() -
Design Multi-language Pack
The above talked about how to initialize multi language pack, the language pack is now designing multi, multi-language package is json file, as described in Chapter X, we need to design a document on LangPath following example zh.json or en.json
# zh.json { "zh": { "submit": "提交", "create": "创建" } } #en.json { "en": { "submit": "Submit", "create": "Create" } } -
Use the Language Pack
We can call the controller to get the response of the translation language translation, as follows:
func (this *MainController) Get() { this.Data["create"] = beego.Translation.Translate("create") this.TplNames = "index.tpl" }We can also directly call response in the template translation function:
// Direct Text translation {{.create | Trans}} // Time to translate {{.time | TransDate}} // Currency translation {{.money | TransMoney}}
Links
- Directory
- Previous section: User validation
- Next section: pprof