GoFrame I18N國際化-使用介紹

2022-04-07 10:16 更新

對(duì)象創(chuàng)建

單例對(duì)象

大多數(shù)場(chǎng)景下,我們推薦使用?g.I18n?單例對(duì)象,并可自定義配置不同的單例對(duì)象,但是需要注意的是,單例對(duì)象的配置修改是全局有效的。例如:

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

在所有的轉(zhuǎn)譯方法中,第一個(gè)參數(shù)都要求輸入?Context?上下文變量參數(shù),用于上下文變量的傳遞、翻譯語言的指定、后續(xù)的可擴(kuò)展能力。該參數(shù)雖然直接傳遞?nil?也是可以的,但是為保證程序的嚴(yán)謹(jǐn)性,我們建議您當(dāng)不知道傳遞什么或者沒有特殊要求的時(shí)候傳遞?context.TODO()?或者?context.Background()?來替代。

獨(dú)立對(duì)象

其次,我們也可以模塊化獨(dú)立使用?gi18n?模塊,通過?gi18n.New()?方法創(chuàng)建獨(dú)立的?i18n?對(duì)象,然后開發(fā)者自行進(jìn)行管理。例如:

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

語言設(shè)置

設(shè)置轉(zhuǎn)譯語言有兩種方式,一種是通過?SetLanguage?方法設(shè)置當(dāng)前?I18N?對(duì)象統(tǒng)一的轉(zhuǎn)譯語言,另一種是通過上下文設(shè)置當(dāng)前執(zhí)行轉(zhuǎn)譯的語言。

SetLanguage

例如,我們通過?g.I18n().SetLanguage("zh-CN")?即可設(shè)置當(dāng)前轉(zhuǎn)譯對(duì)象的轉(zhuǎn)譯語言,隨后使用該對(duì)象都將使用?zh-CN?進(jìn)行轉(zhuǎn)譯。需要注意的是,組件的配置方法往往都不是并發(fā)安全的,該方法也同樣如此,需要在程序初始化時(shí)進(jìn)行設(shè)置,隨后不能在運(yùn)行時(shí)進(jìn)行更改。

WithLanguage

?WithLanguage?方法可以創(chuàng)建一個(gè)新的上下文變量,并臨時(shí)設(shè)置您當(dāng)前轉(zhuǎn)譯的語言,由于該方法作用于?Context?上下文,因此是并發(fā)安全的,常用于運(yùn)行時(shí)轉(zhuǎn)譯語言設(shè)置。我們來看一個(gè)例子:

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

其中?WithLanguage?方法定義如下:

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

用于將轉(zhuǎn)譯語言設(shè)置到上下文變量中,并返回一個(gè)新的上下文變量,該變量可用于后續(xù)的轉(zhuǎn)譯方法。

常用方法

T方法

?T?方法為?Translate?方法的別名,也是大多數(shù)時(shí)候我們推薦使用的方法名稱。?T?方法可以給定關(guān)鍵字名稱,也可以直接給定模板內(nèi)容,將會(huì)被自動(dòng)轉(zhuǎn)譯并返回轉(zhuǎn)譯后的字符串內(nèi)容。

此外,?T?方法可以通過第二個(gè)語言參數(shù)指定需要轉(zhuǎn)譯的目標(biāo)語言名稱,該名稱需要和配置文件/路徑中的名稱一致,往往是標(biāo)準(zhǔn)化的國際化語言縮寫名稱例如:?en/ja/ru/zh-CN/zh-TW?等等。否則,將會(huì)自動(dòng)使用?Manager?轉(zhuǎn)譯對(duì)象中設(shè)置的語言進(jìn)行轉(zhuǎn)譯。

方法定義:

// T translates <content> with configured language and returns the translated content.
func T(ctx context.Context, content string)
  • 關(guān)鍵字轉(zhuǎn)譯

關(guān)鍵字的轉(zhuǎn)譯直接給?T?方法傳遞關(guān)鍵字即可,例如:?T(context.TODO(), "hello")?、?T(context.TODO(), "world")?。?I18N?組件將會(huì)優(yōu)先將給定的關(guān)鍵字進(jìn)行轉(zhuǎn)譯,轉(zhuǎn)譯成后返回轉(zhuǎn)譯后的內(nèi)容,否則直接展示原內(nèi)容。

  • 模板內(nèi)容轉(zhuǎn)譯

?T?方法支持模板內(nèi)容轉(zhuǎn)換,模板中的關(guān)鍵字默認(rèn)使用?{#?和?}?標(biāo)簽進(jìn)行包含,模板解析時(shí)將會(huì)自動(dòng)替換該標(biāo)簽中的關(guān)鍵字內(nèi)容。使用示例:

1)目錄結(jié)構(gòu)

├── main.go
└── i18n
    ├── en.toml
    ├── ja.toml
    ├── ru.toml
    └── zh-CN.toml

2)轉(zhuǎn)譯文件

?ja.toml?

hello = "こんにちは" 
world = "世界"

?ru.toml?

hello = "Привет" 
world = "мир"

?zh-CN.toml ?

hello = "你好" 
world = "世界"

3)示例代碼 

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}!`))
}

執(zhí)行后,終端輸出為:

Hello
GF says: HelloWorld!
こんにちは
GF says: こんにちは世界!
Привет
GF says: Приветмир!
你好
GF says: 你好世界!

Tf方法

我們都知道,模板內(nèi)容中也會(huì)存在一些變量,這些變量可以通過?Tf?方法進(jìn)行轉(zhuǎn)譯。

?Tf?為?TranslateFormat?的別名,該方法支持格式化轉(zhuǎn)譯內(nèi)容,字符串格式化語法參考標(biāo)準(zhǔn)庫?fmt?包的?Sprintf?方法。

  • 方法定義:
// Tf translates, formats and returns the <format> with configured language
// and given <values>.
func Tf(ctx context.Context, format string, values ...interface{}) string

我們來看一個(gè)簡(jiǎn)單的示例。

1)目錄結(jié)構(gòu)

├── main.go
└── i18n
    ├── en.toml
    └── zh-CN.toml

2)轉(zhuǎn)譯文件

?en.toml ?

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

?zh-CN.toml ?

OrderPaid = "您已成功完成訂單號(hào) #%d 支付,支付金額¥%.2f。"

3)示例代碼

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))
}

執(zhí)行后,終端輸出為:

You have successfully complete order #865271654 payment, paid amount: ¥99.80.
您已成功完成訂單號(hào) #865271654 支付,支付金額¥99.80。

為方便演示,該示例中對(duì)支付金額的處理比較簡(jiǎn)單,在實(shí)際項(xiàng)目中往往需要在業(yè)務(wù)代碼中對(duì)支付金額的單位按照區(qū)域做自動(dòng)轉(zhuǎn)換,再渲染?i18n?顯示內(nèi)容。

上下文設(shè)置轉(zhuǎn)譯語言

我們將上面的示例做些改動(dòng)來演示。

1)目錄結(jié)構(gòu)

├── main.go
└── i18n
    ├── en.toml
    └── zh-CN.toml

2)轉(zhuǎn)譯文件

?en.toml

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

?zh-CN.toml?

OrderPaid = "您已成功完成訂單號(hào) #%d 支付,支付金額¥%.2f。"

3)示例代碼

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,
	))
}

執(zhí)行后,終端輸出為:

You have successfully complete order #865271654 payment, paid amount: ¥99.80.
您已成功完成訂單號(hào) #865271654 支付,支付金額¥99.80。

為方便演示,該示例中對(duì)支付金額的處理比較簡(jiǎn)單,在實(shí)際項(xiàng)目中往往需要在業(yè)務(wù)代碼中對(duì)支付金額的單位按照區(qū)域做自動(dòng)轉(zhuǎn)換,再渲染?i18n?顯示內(nèi)容。

I18N與視圖引擎

?gi18n?默認(rèn)已經(jīng)集成到了?GoFrame?框架的視圖引擎中,直接在模板文件/內(nèi)容中使用?gi18n?的關(guān)鍵字標(biāo)簽即可。我們同樣可以通過上下文變量的形式來設(shè)置當(dāng)前請(qǐng)求的轉(zhuǎn)譯語言。

此外,我們也可以通過設(shè)置模板變量?I18nLanguage?設(shè)置當(dāng)前模板的解析語言,該變量可以控制不同的模板內(nèi)容按照不同的國際化語言進(jìn)行解析。

使用示例:

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()
}

執(zhí)行后,訪問以下頁面,將會(huì)輸出:

你好世界!

こんにちは世界!


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)