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:
g.I18n().T(context.TODO(), "{#hello} {#world}")
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:
i18n := gi18n.New()
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:
ctx := gi18n.WithLanguage(context.TODO(), "zh-CN")
i18n.Translate(ctx, `hello`)
The WithLanguage
method is defined as follows:
// WithLanguage append language setting to the context and returns a new context.
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:
// T translates <content> with configured language and returns the translated content.
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
├── main.go
└── i18n
├── en.toml
├── ja.toml
├── ru.toml
└── zh-CN.toml
2) Translation Files
ja.toml
hello = "こんにちは"
world = "世界"
ru.toml
hello = "Привет"
world = "мир"
zh-CN.toml
hello = "你好"
world = "世界"
3) Sample Code
package main
import (
"fmt"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/i18n/gi18n"
)
func main() {
var (
ctx = gctx.New()
i18n = gi18n.New()
)
i18n.SetLanguage("en")
fmt.Println(i18n.Translate(ctx, `hello`))
fmt.Println(i18n.Translate(ctx, `GF says: {#hello}{#world}!`))
i18n.SetLanguage("ja")
fmt.Println(i18n.Translate(ctx, `hello`))
fmt.Println(i18n.Translate(ctx, `GF says: {#hello}{#world}!`))
i18n.SetLanguage("ru")
fmt.Println(i18n.Translate(ctx, `hello`))
fmt.Println(i18n.Translate(ctx, `GF says: {#hello}{#world}!`))
ctx = gi18n.WithLanguage(ctx, "zh-CN")
fmt.Println(i18n.Translate(ctx, `hello`))
fmt.Println(i18n.Translate(ctx, `GF says: {#hello}{#world}!`))
}
After execution, the terminal output is:
Hello
GF says: HelloWorld!
こんにちは
GF says: こんにちは世界!
Привет
GF says: Приветмир!
你好
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:
// Tf translates, formats and returns the <format> with configured language
// and given <values>.
func Tf(ctx context.Context, format string, values ...interface{}) string
Let's take a simple example.
1) Directory Structure
├── main.go
└── i18n
├── en.toml
└── zh-CN.toml
2) Translation Files
en.toml
OrderPaid = "You have successfully complete order #%d payment, paid amount: ¥%0.2f."
zh-CN.toml
OrderPaid = "您已成功完成订单号 #%d 支付,支付金额¥%.2f。"
3) Sample Code
package main
import (
"fmt"
"github.com/gogf/gf/v2/i18n/gi18n"
"github.com/gogf/gf/v2/os/gctx"
)
func main() {
var (
ctx = gctx.New()
orderId = 865271654
orderAmount = 99.8
)
i18n := gi18n.New()
i18n.SetLanguage("en")
fmt.Println(i18n.Tf(ctx, `{#OrderPaid}`, orderId, orderAmount))
i18n.SetLanguage("zh-CN")
fmt.Println(i18n.Tf(ctx, `{#OrderPaid}`, orderId, orderAmount))
}
After execution, the terminal output is:
You have successfully complete order #865271654 payment, paid amount: ¥99.80.
您已成功完成订单号 #865271654 支付,支付金额¥99.80。
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
├── main.go
└── i18n
├── en.toml
└── zh-CN.toml
2) Translation Files
en.toml
OrderPaid = "You have successfully complete order #%d payment, paid amount: ¥%0.2f."
zh-CN.toml
OrderPaid = "您已成功完成订单号 #%d 支付,支付金额¥%.2f。"
3) Sample Code
package main
import (
"context"
"fmt"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/i18n/gi18n"
)
func main() {
var (
orderId = 865271654
orderAmount = 99.8
)
fmt.Println(g.I18n().Tf(
gi18n.WithLanguage(context.TODO(), `en`),
`{#OrderPaid}`, orderId, orderAmount,
))
fmt.Println(g.I18n().Tf(
gi18n.WithLanguage(context.TODO(), `zh-CN`),
`{#OrderPaid}`, orderId, orderAmount,
))
}
After execution, the terminal output is:
You have successfully complete order #865271654 payment, paid amount: ¥99.80.
您已成功完成订单号 #865271654 支付,支付金额¥99.80。
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.
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:
package main
import (
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/i18n/gi18n"
"github.com/gogf/gf/v2/net/ghttp"
)
func main() {
s := g.Server()
s.Group("/", func(group *ghttp.RouterGroup) {
group.Middleware(func(r *ghttp.Request) {
r.SetCtx(gi18n.WithLanguage(r.Context(), r.GetString("lang", "zh-CN")))
r.Middleware.Next()
})
group.ALL("/", func(r *ghttp.Request) {
r.Response.WriteTplContent(`{#hello}{#world}!`)
})
})
s.SetPort(8199)
s.Run()
}
After execution, visit the following pages, and the output will be:
-
你好世界!
-
http://127.0.0.1:8199/?lang=ja
こんにちは世界!