如何使用beego的本地化?

时间:2015-05-25 23:03:59

标签: go beego

我尝试使用i18n,但它无法正常工作 i18n在下面。 http://beego.me/docs/module/i18n.md

路由器/ init.go:

// Initialized language type list.
langs := strings.Split(models.Cfg.MustValue("lang", "types"), "|")
names := strings.Split(models.Cfg.MustValue("lang", "names"), "|")
langTypes = make([]*langType, 0, len(langs))
for i, v := range langs {
    langTypes = append(langTypes, &langType{
        Lang: v,
        Name: names[i],
    })
}

for _, lang := range langs {
    beego.Trace("Loading language: " + lang)
    if err := i18n.SetMessage(lang, "conf/"+"locale_"+lang+".ini"); err != nil {
        beego.Error("Fail to set message file: " + err.Error())
        return
    }
}

路由器/ router.go

// Initialized language type list.
langs := strings.Split(models.Cfg.MustValue("lang", "types"), "|")
names := strings.Split(models.Cfg.MustValue("lang", "names"), "|")
langTypes = make([]*langType, 0, len(langs))
for i, v := range langs {
    langTypes = append(langTypes, &langType{
        Lang: v,
        Name: names[i],
    })
}

for _, lang := range langs {
    beego.Trace("Loading language: " + lang)
    if err := i18n.SetMessage(lang, "conf/"+"locale_"+lang+".ini"); err != nil {
        beego.Error("Fail to set message file: " + err.Error())
        return
    }
}

我刚复制并粘贴。

这是我的完整代码。 https://github.com/shinriyo/sample_i18n

我想知道最少的代码。

是错误

bee run
2015/05/24 17:48:56 [INFO] Uses 'sample_i18n' as 'appname'
2015/05/24 17:48:56 [INFO] Initializing watcher...
2015/05/24 17:48:56 [TRAC] Directory(/Users/shinriyo/src/sample_i18n/controllers)
2015/05/24 17:48:56 [TRAC] Directory(/Users/shinriyo/src/sample_i18n)
2015/05/24 17:48:56 [TRAC] Directory(/Users/shinriyo/src/sample_i18n/routers)
2015/05/24 17:48:56 [TRAC] Directory(/Users/shinriyo/src/sample_i18n/tests)
2015/05/24 17:48:56 [INFO] Start building...
main.go:4:2:
routers/init.go:2:1: expected 'package', found 'IDENT' langs
2015/05/24 17:48:56 [ERRO] ============== Build failed ===================

2 个答案:

答案 0 :(得分:0)

我发现的最好方法是:

  1. 在conf /文件夹
  2. 中创建翻译文件
  3. 在conf / app.conf中配置您的翻译列表。我的语言是en-US和pt-BR

    lang_types = "en-US|pt-BR"
    
  4. 在controller / baseController /文件夹中创建文件baseController.go 使用此代码

    package controllers
    import (
          "github.com/astaxie/beego"
          "github.com/beego/i18n"
          "strings"
    )
    var langTypes []string // Languages that are supported.
    // baseController represents base router for all other app routers.
    // It implemented some methods for the same implementation;
    // thus, it will be embedded into other routers.
    type BaseController struct {
        beego.Controller // Embed struct that has stub implementation of the                     interface.
        i18n.Locale      // For i18n usage when process data and render template.
    }
    
    func init() {
        beego.AddFuncMap("i18n", i18n.Tr)
    
        // Initialize language type list.
        langTypes = strings.Split(beego.AppConfig.String("lang_types"), "|")
    
        // Load locale files according to language types.
        for _, lang := range langTypes {
            beego.Trace("Loading language: " + lang)
            if err := i18n.SetMessage(lang, "conf/"+"locale_"+lang+".ini"); err != nil {
                beego.Error("Fail to set message file:", err)
                return
            }
        }
    }
    
    // Prepare implemented Prepare() method for baseController.
    // It's used for language option check and setting.
    func (this *BaseController) Prepare() {
        // Reset language option.
        this.Lang = "" // This field is from i18n.Locale.
        beego.Trace("running prepare")
        // 1. Get language information from 'Accept-Language'.
        al := this.Ctx.Request.Header.Get("Accept-Language")
        if len(al) > 4 {
            al = al[:5] // Only compare first 5 letters.
            if i18n.IsExist(al) {
                this.Lang = al
            }
        }
    
        beego.Trace("Accept-Language is " + al)
        // 2. Default language is English.
        if len(this.Lang) == 0 {
            this.Lang = "en-US"
        }
    
        // Set template level language option.
        this.Data["Lang"] = this.Lang
    }
    
  5. 在其他控制器中使用自定义BaseController。

    package controllers
    
    import (
        bc "github.com/myFirstApp/controllers/baseController"
    )
    
    type LoginController struct {
        bc.BaseController
    }
    
    func (c *LoginController) Get() {
        c.TplNames = "login.tpl"
    }
    
  6. 在模板中使用i18n

    {{i18n .Lang "login.capitalized"}}
    
  7. 我的locale_en-US.ini

        login = login
        [login]
        uppercase = LOGIN
        capitalized = Login
    

答案 1 :(得分:0)

package controllers

import (
    "github.com/astaxie/beego"
    "github.com/beego/i18n"
    "os"
    "strings"
)

type BaseController struct {
    beego.Controller
}

func (b *BaseController) settingLocales() {
    // load locales with locale_LANG.ini files
    langs := "en-US|zh-CN"
    for _, lang := range strings.Split(langs, "|") {
        lang = strings.TrimSpace(lang)
        files := []string{"conf/" + "locale_" + lang + ".ini"}
        if fh, err := os.Open(files[0]); err == nil {
            fh.Close()
        } else {
            files = nil
        }
        if err := i18n.SetMessage(lang, "conf/"+"locale_"+lang+".ini", files...); err != nil {
            beego.Error("Fail to set message file: " + err.Error())
            os.Exit(2)
        }
    }
    Las := i18n.ListLangs()
    beego.Debug("langs:", Las)
}

func (b *BaseController) Get() {
    b.settingLocales()
    if i18n.IsExist("en-US") {
        b.Data["json"] = i18n.Tr("en-US", "hi")
    } else {
        b.Data["json"] = s
    }
    b.ServeJson()
}

在conf /

中创建文件locale_en-US.ini和locale_zh-CN.ini 在locale_en-US.ini中的

如:

hi = hello
bye = goodbye