i18n

This module is mainly used for i18n of sites and applications, which provides multiple-language options to users, improve user experience.

You can use the following command to install this module:

go get github.com/beego/i18n@latest

i18n Usage

First of all, you have to import this package:

  1. import (
  2. "github.com/beego/i18n"
  3. )

The format of locale files is very much like the INI format configuration file, which is basically key-value pairs. But this module has some improvements. Every language corresponds to a locale file, for example, under conf folder of beego.vip, there are two files called locale_en-US.ini and locale_zh-CN.ini.

The name and extensions of locale files can be anything.

Minimal example

Here are two simplest locale file examples:

File locale_en-US.ini:

  1. hi = hello
  2. bye = goodbye

File locale_zh-CN.ini:

  1. hi = 您好
  2. bye = 再见

Use in controller

For every request, Beego uses individual goroutines to handle the request; therefore, you can embed an i18n.Locale as an anonymous field to process locale operations of the current request. This requires that you understand the idea of baseController and Prepare method. See source file routers/router.go of beego.vip for more details.

After accepting the request, use the Prepare method of baseController to do language operations, which you only need to write the same code once and use it in all the upper level controllers.

Register locale files

The following code is from beego.vip source file routers/init.go:

  1. // Initialized language type list.
  2. langs := strings.Split(beego.AppConfig.String("lang::types"), "|")
  3. names := strings.Split(beego.AppConfig.String("lang::names"), "|")
  4. langTypes = make([]*langType, 0, len(langs))
  5. for i, v := range langs {
  6. langTypes = append(langTypes, &langType{
  7. Lang: v,
  8. Name: names[i],
  9. })
  10. }
  11. for _, lang := range langs {
  12. beego.Trace("Loading language: " + lang)
  13. if err := i18n.SetMessage(lang, "conf/"+"locale_"+lang+".ini"); err != nil {
  14. beego.Error("Fail to set message file: " + err.Error())
  15. return
  16. }
  17. }

In this piece of code, we get languages that we want to support in the configuration file, in this case, we have en-US and zh-CN. Then we initialize a slice for users to change language option(not discussed here). Finally, we call the i18n.SetMessage function in a loop to load all the locale files. Here you can see why we recommend the you use the naming conventions of beego.vip for locale files.

Initialize controller language

The following code is from the beego.vip source file routers/router.go, which decides on which user language option to use in the following order: 1: URL specified 2: Cookies and 3: browser Accept-Language.

  1. // setLangVer sets site language version.
  2. func (this *baseRouter) setLangVer() bool {
  3. isNeedRedir := false
  4. hasCookie := false
  5. // 1. Check URL arguments.
  6. lang := this.Input().Get("lang")
  7. // 2. Get language information from cookies.
  8. if len(lang) == 0 {
  9. lang = this.Ctx.GetCookie("lang")
  10. hasCookie = true
  11. } else {
  12. isNeedRedir = true
  13. }
  14. // Check again in case someone modify on purpose.
  15. if !i18n.IsExist(lang) {
  16. lang = ""
  17. isNeedRedir = false
  18. hasCookie = false
  19. }
  20. // 3. Get language information from 'Accept-Language'.
  21. if len(lang) == 0 {
  22. al := this.Ctx.Request.Header.Get("Accept-Language")
  23. if len(al) > 4 {
  24. al = al[:5] // Only compare first 5 letters.
  25. if i18n.IsExist(al) {
  26. lang = al
  27. }
  28. }
  29. }
  30. // 4. Default language is English.
  31. if len(lang) == 0 {
  32. lang = "en-US"
  33. isNeedRedir = false
  34. }
  35. curLang := langType{
  36. Lang: lang,
  37. }
  38. // Save language information in cookies.
  39. if !hasCookie {
  40. this.Ctx.SetCookie("lang", curLang.Lang, 1<<31-1, "/")
  41. }
  42. restLangs := make([]*langType, 0, len(langTypes)-1)
  43. for _, v := range langTypes {
  44. if lang != v.Lang {
  45. restLangs = append(restLangs, v)
  46. } else {
  47. curLang.Name = v.Name
  48. }
  49. }
  50. // Set language properties.
  51. this.Lang = lang
  52. this.Data["Lang"] = curLang.Lang
  53. this.Data["CurLang"] = curLang.Name
  54. this.Data["RestLangs"] = restLangs
  55. return isNeedRedir
  56. }

The variable isNeedRedir indicates whether user uses URL to specify the language option. To keep the URL clean, beego.vip automatically sets the value in cookies and redirect.

The line this.Data["Lang"] = curLang.Lang sets user language option to template variable Lang so that we can handle language in template files.

Following two lines:

  1. this.Data["CurLang"] = curLang.Name
  2. this.Data["RestLangs"] = restLangs

For users to change language option, see beego.vip source code for more details.

Handle language in controller

While the i18n.Locale is an anonymous field to be embedded in baseController, we can use this.Tr(format string, args ...interface{}) to handle language in controller.

Handle language in template

By passing template variable Lang to indicate language option, you are able to do localization in template. But before that, you need to register a template function.

Following code is from beego.vip source file beeweb.go:

  1. beego.AddFuncMap("i18n", i18n.Tr)

After that, do the following with Lang to handle language:

  1. {{i18n .Lang "hi%d" 12}}

Code above will produce:

  • English en-UShello12
  • Chinese zh-CN您好12

Section

For different pages, one key may map to different values. Therefore, i18n module also uses the section feature of INI format configuration to achieve section separation.

For example, the key name is about, and we want to show About in the home page and About Us in about page. Then you can do following:

Content in locale file:

  1. about = About
  2. [about]
  3. about = About Us

Get about in home page:

  1. {{i18n .Lang "about"}}

Get about in about page:

  1. {{i18n .Lang "about.about"}}

Ambiguity

Because dot . denotes a section in both INI parser and locale files, when your key name contains . this will cause ambiguity. To avoid ambiguity, you just need to add one more . in front of the key.

For example, the key name is about., then we can use:

  1. {{i18n .Lang ".about."}}

to get the desired result.

Helper tool

Module i18n provides a command line helper tool beei18n to simplify the steps in your development. You can install it as follows:

  1. go get github.com/beego/i18n/beei18n

Sync locale files

Command sync allows you use a exist local file as the template to create or sync other locale files:

  1. beei18n sync source_file.ini other1.ini other2.ini

This command can operate on 1 or more files in one command.

More information

If the key does not exist, then i18n will return the key string to caller. For instance, when key name is hi and it does not exist in locale file, it will simply return hi as output.