example: i18n: nested .ini template key-values

This commit is contained in:
Gerasimos (Makis) Maropoulos 2020-09-14 22:00:20 +03:00
parent 44d5ebdc9c
commit 0f7cf7f35c
No known key found for this signature in database
GPG Key ID: 5DBE766BD26A54E7
5 changed files with 43 additions and 3 deletions

View File

@ -0,0 +1,10 @@
[nav]
User = Λογαριασμός
[debug]
Title = Μενού προγραμματιστή
AccessLog = Πρόσβαση στο αρχείο καταγραφής
AccessLogClear = Καθαρισμός {{tr "debug.AccessLog"}}
[user.connections]
Title = {{tr "nav.User"}} Συνδέσεις

View File

@ -0,0 +1,12 @@
# just an example of some more nested keys,
# see /other endpoint.
[nav]
User = Account
[debug]
Title = Developer Menu
AccessLog = Access Log
AccessLogClear = Clear {{tr "debug.AccessLog"}}
[user.connections]
Title = {{tr "nav.User"}} Connections

View File

@ -46,7 +46,10 @@ func newApp() *iris.Application {
} }
} }
app.I18n.Load("./locales/*/*", "en-US", "el-GR") err := app.I18n.Load("./locales/*/*", "en-US", "el-GR")
if err != nil {
panic(err)
}
app.Get("/", func(ctx iris.Context) { app.Get("/", func(ctx iris.Context) {
text := ctx.Tr("HiDogs", iris.Map{ text := ctx.Tr("HiDogs", iris.Map{
@ -69,5 +72,11 @@ func newApp() *iris.Application {
ctx.WriteString(text) ctx.WriteString(text)
}) })
// showcases the other.ini translation file.
app.Get("/other", func(ctx iris.Context) {
ctx.Writef(`AccessLogClear: %s
Title: %s`, ctx.Tr("debug.AccessLogClear"), ctx.Tr("user.connections.Title"))
})
return app return app
} }

View File

@ -18,4 +18,9 @@ func TestI18nLoaderFuncMap(t *testing.T) {
Body().Equal("There are 42 members registered") Body().Equal("There are 42 members registered")
e.GET("/").WithHeader("Accept-Language", "el").Expect().Status(httptest.StatusOK). e.GET("/").WithHeader("Accept-Language", "el").Expect().Status(httptest.StatusOK).
Body().Equal("Γειά 2 σκυλί") Body().Equal("Γειά 2 σκυλί")
e.GET("/other").Expect().Status(httptest.StatusOK).
Body().Equal("AccessLogClear: Clear Access Log\nTitle: Account Connections")
e.GET("/other").WithHeader("Accept-Language", "el").Expect().Status(httptest.StatusOK).
Body().Equal("AccessLogClear: Καθαρισμός Πρόσβαση στο αρχείο καταγραφής\nTitle: Λογαριασμός Συνδέσεις")
} }

View File

@ -287,11 +287,15 @@ func (l *defaultLocale) GetMessageContext(ctx *context.Context, key string, args
} }
func (l *defaultLocale) getMessage(langInput, key string, args ...interface{}) string { func (l *defaultLocale) getMessage(langInput, key string, args ...interface{}) string {
// search on templates. // search on templates.
if tmpl, ok := l.templateKeys[key]; ok { if tmpl, ok := l.templateKeys[key]; ok {
var data interface{}
if len(args) > 0 {
data = args[0]
}
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
err := tmpl.Execute(buf, args[0]) err := tmpl.Execute(buf, data)
if err != nil { if err != nil {
return err.Error() return err.Error()
} }