go-i18n

command module
v0.0.2-beta1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2021 License: MIT Imports: 3 Imported by: 0

README

go-i18n

是什么

一个为项目添加本地化和国际化支持的golang库,该库很大程度上受nicksnyder/go-i18n的启发

怎么用

在项目中引入依赖,并声明一些Message对象,ID必须唯一,Text中写入需要翻译的字符串,支持go template语法

var (
	jan = translation.Message{ID: "January", Text: "January"}
	greeting = translation.Message{ID: "Hello", Text: "Hello"}
	format = translation.Message{ID: "DayOfMonth", Text: "The {{.Day}}(th) day of {{.Month}}"}
	ways = translation.Message{ID: "TwoWay", Text: "One way is to {{.One}}, the other is to {{.Other}}"}
	roma = translation.Message{ID: "roma", Text: "roma"}
	paris = translation.Message{ID: "paris", Text: "paris"}
	text = translation.Message{ID: "text", Text: "{{.}}"}
)

使用go-i18n extract 命令生成原语言的json文件

go-i18n extract -o ./i18n main.go

准备若干种语言对应的翻译,文件名需要符合golang.org/x/text/language中对语言的定义,并且以.json结尾

en.json

[
  {
    "id":"TwoWay",
    "text":"One way is to {{.One}}, the other is to {{.Other}}"
  },
  {
    "id":"January",
    "text":"January"
  },
  {
    "id":"Hello",
    "text":"Hello"
  },
  {
    "id":"roma",
    "text":"roma"
  },
  {
    "id":"paris",
    "text":"paris"
  },
  {
    "id":"DayOfMonth",
    "text":"The {{.Day}}(th) day of {{.Month}}"
  },
  {
    "id":"text",
    "text":"{{.}}"
  }
]

对于每个需要翻译的条目,id是唯一的,text内的文字支持go-template模板语法。翻译完成后将所有文件放到一个文件夹中。

在main函数中加载翻译

translation.LoadTranslations(`C:\Users\aagui\IdeaProjects\go-i18n\i18n`)

可以设置默认语言,这样Message在调用String方法时便会根据默认语言输出文本。

translation.SetDefaultLocale(lang.English)

也可以用Translate方法指定输出的语言。为Message对象设置的输出语言,会传递给其所引用的Message对象。否则,默认语言会被传递。

fmt.Println(greeting.Translate(lang.SimplifiedChinese))
fmt.Println(format.FormatTranslate(lang.SimplifiedChinese, translation.TemplateData{"Day": 2, "Month": jan}))
fmt.Println(ways.Format(translation.TemplateData{"One": roma, "Other": paris}))

Documentation

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis
cmd
pkg
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL