diff --git a/context.go b/context.go index 82d1c27..8de487c 100644 --- a/context.go +++ b/context.go @@ -1,5 +1,7 @@ package html +import i18n "dappco.re/go/core/i18n" + // context.go: Translator provides Text() lookups for a rendering context. // Example: a locale-aware service can satisfy T(key, args...). type Translator interface { @@ -59,10 +61,12 @@ func normaliseContext(ctx *Context) *Context { // An optional locale may be provided as the first argument. func NewContext(locale ...string) *Context { ctx := &Context{ - Data: make(map[string]any), + Data: make(map[string]any), + service: &i18n.Service{}, } if len(locale) > 0 { ctx.Locale = locale[0] + applyLocaleToService(ctx.service, ctx.Locale) } return ctx } diff --git a/context_test.go b/context_test.go index dfd31dc..f09aea8 100644 --- a/context_test.go +++ b/context_test.go @@ -36,6 +36,14 @@ func TestContext_NewContextWithService_AppliesLocale(t *testing.T) { } } +func TestContext_NewContext_AppliesLocaleToDefaultService(t *testing.T) { + ctx := NewContext("fr-FR") + + if got := Text("prompt.yes").Render(ctx); got != "o" { + t.Fatalf("NewContext(locale) translation = %q, want %q", got, "o") + } +} + func TestContext_NewContextWithService_UsesLocale(t *testing.T) { svc := &localeTranslator{} ctx := NewContextWithService(svc, "en-GB") diff --git a/deps/go-i18n/i18n.go b/deps/go-i18n/i18n.go index 244f6e9..eeb52ba 100644 --- a/deps/go-i18n/i18n.go +++ b/deps/go-i18n/i18n.go @@ -1,9 +1,14 @@ package i18n -import "fmt" +import ( + "fmt" + "strings" +) // Service is a minimal translation service for local verification. -type Service struct{} +type Service struct { + language string +} var defaultService = &Service{} @@ -20,6 +25,23 @@ func SetDefault(svc *Service) { defaultService = svc } +// SetLanguage records the active language for locale-aware lookups. +func (s *Service) SetLanguage(language string) error { + if s == nil { + return nil + } + + base := language + for i := 0; i < len(base); i++ { + if base[i] == '-' || base[i] == '_' { + base = base[:i] + break + } + } + s.language = strings.ToLower(base) + return nil +} + // T returns a translated string for key. func T(key string, args ...any) string { return defaultService.T(key, args...) @@ -27,6 +49,17 @@ func T(key string, args ...any) string { // T returns a translated string for key. func (s *Service) T(key string, args ...any) string { + if s != nil { + switch key { + case "prompt.yes": + switch s.language { + case "fr": + return "o" + case "en": + return "y" + } + } + } if len(args) == 0 { return key }