Object Creation

Singleton Object

In most scenarios, we recommend using the g.I18n singleton object and allowing customization of different singleton objects. However, it is important to note that modifications to the configuration of a singleton object are globally effective. For example:

  1. g.I18n().T(context.TODO(), "{#hello} {#world}")

I18N - Example - 图1tip

In all translation methods, the first parameter requires the input of a Context context variable parameter, which is used for context variable transmission, specifying the translation language, and for future extensibility. Although this parameter can also be directly passed as nil, for the sake of program rigor, it is recommended that you pass context.TODO() or context.Background() when you are unsure of what to pass or have no special requirements.

Independent Object

Alternatively, we can modularly use the gi18n module independently by creating an independent i18n object with the gi18n.New() method, then managed by the developer. For example:

  1. i18n := gi18n.New()
  2. i18n.T(context.TODO(), "{#hello} {#world}")

Language Setting

There are two ways to set the translation language: one is through the SetLanguage method to set a unified translation language for the current I18N object, and the other is through context setting for the language of the currently executing translation.

SetLanguage

For example, we can set the current translation object’s language with g.I18n().SetLanguage("zh-CN"). Thereafter, any usage of this object will perform translation in zh-CN. It is important to note that the configuration method of the component is also not concurrency-safe, and this method should be set during program initialization and not be changed during runtime.

WithLanguage

The WithLanguage method can create a new context variable and temporarily set the language of your current translation. Since this method acts on the Context, it is concurrency-safe and is often used for runtime translation language setting. Let’s see an example:

  1. ctx := gi18n.WithLanguage(context.TODO(), "zh-CN")
  2. i18n.Translate(ctx, `hello`)

The WithLanguage method is defined as follows:

  1. // WithLanguage append language setting to the context and returns a new context.
  2. func WithLanguage(ctx context.Context, language string) context.Context

It is used to set the translation language in the context variable and return a new context variable, which can be used for subsequent translation methods.

Common Methods

T Method

The T method is an alias for the Translate method, and it’s the name we recommend using most of the time. The T method can take a keyword name or be directly given template content, and it will automatically translate and return the translated string.

Additionally, the T method can specify the target language name to be translated through a second language parameter. This name should match those in the configuration files/paths and is often a standardized international language abbreviation such as: en/ja/ru/zh-CN/zh-TW, etc. Otherwise, it will automatically use the language set in the Manager translation object for translation.

Method definition:

  1. // T translates <content> with configured language and returns the translated content.
  2. func T(ctx context.Context, content string)

Keyword Translation

For keyword translation, simply pass the keyword to the T method, such as: T(context.TODO(), "hello"), T(context.TODO(), "world"). The I18N component will prioritize translating the given keyword and return the translated content; otherwise, the original content is displayed.

Template Content Translation

The T method supports template content translation, where keywords in the template are by default enclosed using {# and } tags. During template parsing, it will automatically replace the keyword contents within these tags. Example usage:

1) Directory Structure

  1. ├── main.go
  2. └── i18n
  3. ├── en.toml
  4. ├── ja.toml
  5. ├── ru.toml
  6. └── zh-CN.toml

2) Translation Files

ja.toml

  1. hello = "こんにちは"
  2. world = "世界"

ru.toml

  1. hello = "Привет"
  2. world = "мир"

zh-CN.toml

  1. hello = "你好"
  2. world = "世界"

3) Sample Code

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/os/gctx"
  5. "github.com/gogf/gf/v2/i18n/gi18n"
  6. )
  7. func main() {
  8. var (
  9. ctx = gctx.New()
  10. i18n = gi18n.New()
  11. )
  12. i18n.SetLanguage("en")
  13. fmt.Println(i18n.Translate(ctx, `hello`))
  14. fmt.Println(i18n.Translate(ctx, `GF says: {#hello}{#world}!`))
  15. i18n.SetLanguage("ja")
  16. fmt.Println(i18n.Translate(ctx, `hello`))
  17. fmt.Println(i18n.Translate(ctx, `GF says: {#hello}{#world}!`))
  18. i18n.SetLanguage("ru")
  19. fmt.Println(i18n.Translate(ctx, `hello`))
  20. fmt.Println(i18n.Translate(ctx, `GF says: {#hello}{#world}!`))
  21. ctx = gi18n.WithLanguage(ctx, "zh-CN")
  22. fmt.Println(i18n.Translate(ctx, `hello`))
  23. fmt.Println(i18n.Translate(ctx, `GF says: {#hello}{#world}!`))
  24. }

After execution, the terminal output is:

  1. Hello
  2. GF says: HelloWorld!
  3. こんにちは
  4. GF says: こんにちは世界!
  5. Привет
  6. GF says: Приветмир!
  7. 你好
  8. GF says: 你好世界!

Tf Method

We know that there will also be some variables in the template content, and these variables can be translated with the Tf method.

Tf is an alias for TranslateFormat. This method supports formatting translated content, and the string formatting syntax refers to the Sprintf method of the standard library fmt package.

Method Definition:

  1. // Tf translates, formats and returns the <format> with configured language
  2. // and given <values>.
  3. func Tf(ctx context.Context, format string, values ...interface{}) string

Let’s take a simple example.

1) Directory Structure

  1. ├── main.go
  2. └── i18n
  3. ├── en.toml
  4. └── zh-CN.toml

2) Translation Files

en.toml

  1. OrderPaid = "You have successfully complete order #%d payment, paid amount: ¥%0.2f."

zh-CN.toml

  1. OrderPaid = "您已成功完成订单号 #%d 支付,支付金额¥%.2f。"

3) Sample Code

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/i18n/gi18n"
  5. "github.com/gogf/gf/v2/os/gctx"
  6. )
  7. func main() {
  8. var (
  9. ctx = gctx.New()
  10. orderId = 865271654
  11. orderAmount = 99.8
  12. )
  13. i18n := gi18n.New()
  14. i18n.SetLanguage("en")
  15. fmt.Println(i18n.Tf(ctx, `{#OrderPaid}`, orderId, orderAmount))
  16. i18n.SetLanguage("zh-CN")
  17. fmt.Println(i18n.Tf(ctx, `{#OrderPaid}`, orderId, orderAmount))
  18. }

After execution, the terminal output is:

  1. You have successfully complete order #865271654 payment, paid amount: ¥99.80.
  2. 您已成功完成订单号 #865271654 支付,支付金额¥99.80。

I18N - Example - 图2note

For demonstration purposes, the handling of the payment amount in this example is quite simple. In actual projects, it is often necessary to automatically convert the currency unit according to the region in the business code before rendering the i18n display content.

Context setting for translation language

We will make some changes to the above example for demonstration.

1) Directory Structure

  1. ├── main.go
  2. └── i18n
  3. ├── en.toml
  4. └── zh-CN.toml

2) Translation Files

en.toml

  1. OrderPaid = "You have successfully complete order #%d payment, paid amount: ¥%0.2f."

zh-CN.toml

  1. OrderPaid = "您已成功完成订单号 #%d 支付,支付金额¥%.2f。"

3) Sample Code

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gogf/gf/v2/frame/g"
  6. "github.com/gogf/gf/v2/i18n/gi18n"
  7. )
  8. func main() {
  9. var (
  10. orderId = 865271654
  11. orderAmount = 99.8
  12. )
  13. fmt.Println(g.I18n().Tf(
  14. gi18n.WithLanguage(context.TODO(), `en`),
  15. `{#OrderPaid}`, orderId, orderAmount,
  16. ))
  17. fmt.Println(g.I18n().Tf(
  18. gi18n.WithLanguage(context.TODO(), `zh-CN`),
  19. `{#OrderPaid}`, orderId, orderAmount,
  20. ))
  21. }

After execution, the terminal output is:

  1. You have successfully complete order #865271654 payment, paid amount: ¥99.80.
  2. 您已成功完成订单号 #865271654 支付,支付金额¥99.80。

I18N - Example - 图3note

For demonstration purposes, the handling of the payment amount in this example is quite simple. In actual projects, it is often necessary to automatically convert the currency unit according to the region in the business code before rendering the i18n display content.

I18N and the View Engine

gi18n is already integrated into the GoFrame framework’s view engine by default, allowing you to directly use gi18n keyword tags in template files/content. We can also set the translation language of the current request through context variables.

I18N - Example - 图4tip

Additionally, we can set the template variable I18nLanguage to control the parsing language of the current template, allowing different template content to be parsed according to different international languages.

Usage example:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/i18n/gi18n"
  5. "github.com/gogf/gf/v2/net/ghttp"
  6. )
  7. func main() {
  8. s := g.Server()
  9. s.Group("/", func(group *ghttp.RouterGroup) {
  10. group.Middleware(func(r *ghttp.Request) {
  11. r.SetCtx(gi18n.WithLanguage(r.Context(), r.GetString("lang", "zh-CN")))
  12. r.Middleware.Next()
  13. })
  14. group.ALL("/", func(r *ghttp.Request) {
  15. r.Response.WriteTplContent(`{#hello}{#world}!`)
  16. })
  17. })
  18. s.SetPort(8199)
  19. s.Run()
  20. }

After execution, visit the following pages, and the output will be:

  1. http://127.0.0.1:8199

    1. 你好世界!
  2. http://127.0.0.1:8199/?lang=ja

    1. こんにちは世界!