improve key words transaction for package i18n (#2652)

This commit is contained in:
aries 2023-06-06 21:03:25 +08:00 committed by GitHub
parent 835b252b5d
commit 1bbfc56121
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 20 additions and 6 deletions

View File

@ -68,7 +68,7 @@ func New(options ...Options) *Manager {
m := &Manager{
options: opts,
pattern: fmt.Sprintf(
`%s(\w+)%s`,
`%s(.+?)%s`,
gregex.Quote(opts.Delimiters[0]),
gregex.Quote(opts.Delimiters[1]),
),
@ -122,7 +122,7 @@ func (m *Manager) SetLanguage(language string) {
// SetDelimiters sets the delimiters for translator.
func (m *Manager) SetDelimiters(left, right string) {
m.pattern = fmt.Sprintf(`%s(\w+)%s`, gregex.Quote(left), gregex.Quote(right))
m.pattern = fmt.Sprintf(`%s(.+?)%s`, gregex.Quote(left), gregex.Quote(right))
intlog.Printf(context.TODO(), `SetDelimiters: %v`, m.pattern)
}
@ -166,6 +166,8 @@ func (m *Manager) Translate(ctx context.Context, content string) string {
if v, ok := data[match[1]]; ok {
return v
}
// return match[1] will return the content between delimiters
// return match[0] will return the original content
return match[0]
})
intlog.Printf(ctx, `Translate for language: %s`, transLang)

View File

@ -39,6 +39,10 @@ func Test_Basic(t *testing.T) {
i18n.SetDelimiters("{$", "}")
t.Assert(i18n.T(context.Background(), "{#hello}{#world}"), "{#hello}{#world}")
t.Assert(i18n.T(context.Background(), "{$hello}{$world}"), "你好世界")
t.Assert(i18n.T(context.Background(), "{#hello}{#world}"), "{#hello}{#world}")
t.Assert(i18n.T(context.Background(), "{$你好} {$世界}"), "hello world")
// undefined variables.
t.Assert(i18n.T(context.Background(), "{$你好1}{$世界1}"), "{$你好1}{$世界1}")
})
gtest.C(t, func(t *gtest.T) {
@ -53,6 +57,7 @@ func Test_Basic(t *testing.T) {
i18n.SetLanguage("zh-CN")
t.Assert(i18n.T(context.Background(), "{#hello}{#world}"), "你好世界")
t.Assert(i18n.T(context.Background(), "{#你好} {#世界}"), "hello world")
})
gtest.C(t, func(t *gtest.T) {
@ -122,6 +127,7 @@ func Test_Instance(t *testing.T) {
t.AssertNil(err)
m.SetLanguage("zh-CN")
t.Assert(m.T(context.Background(), "{#hello}{#world}"), "你好世界")
t.Assert(m.T(context.Background(), "{#你好} {#世界}"), "hello world")
})
gtest.C(t, func(t *gtest.T) {

View File

@ -1,4 +1,6 @@
{
"hello": "你好",
"world": "世界"
"你好": "hello",
"世界": "world",
"hello": "你好",
"world": "世界"
}

6
i18n/gi18n/testdata/i18n/zh-CN.json vendored Normal file
View File

@ -0,0 +1,6 @@
{
"你好": "hello",
"世界": "world",
"hello": "你好",
"world": "世界"
}

View File

@ -1,2 +0,0 @@
hello = "你好"
world = "世界"