0

我尝试使用 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 ===================
4

2 回答 2

0

我发现的最好方法是:

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

    lang_types = "en-US|pt-BR"
    
  3. 使用此代码在 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
    }
    
  4. 在其他控制器中使用您的自定义 BaseController。

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

    {{i18n .Lang "login.capitalized"}}
    

我的 locale_en-US.ini

    login = login
    [login]
    uppercase = LOGIN
    capitalized = Login
于 2015-11-13T12:10:37.937 回答
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
于 2016-01-14T09:30:51.800 回答