We introduced in Chapter internationalization and localization, we developed a go-i18n library, the library this section we will integrate beego frame inside, making our framework supports internationalization and localization.
beego global variable is set as follows:
Translation i18n.IL
Lang string // set the language pack, zh, en
LangPath string // set the language pack location
Multi-language function to initialize:
func InitLang(){
beego.Translation:=i18n.NewLocale()
beego.Translation.LoadPath(beego.LangPath)
beego.Translation.SetLocale(beego.Lang)
}
In order to facilitate more direct call in the template language pack, we have designed three functions to handle the response of multiple languages:
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)
}
-
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}}
- Directory
- Previous section: User validation
- Next section: pprof