diff --git a/service.go b/service.go index c4fd078..188de6a 100644 --- a/service.go +++ b/service.go @@ -472,11 +472,32 @@ func (s *Service) getEffectiveContextGenderLocationAndFormality(data any) (strin } func (s *Service) getEffectiveContextExtra(data any) map[string]any { - ctx, ok := data.(*TranslationContext) - if !ok || ctx == nil || len(ctx.Extra) == 0 { + switch v := data.(type) { + case *TranslationContext: + if v == nil || len(v.Extra) == 0 { + return nil + } + return v.Extra + case map[string]any: + if len(v) == 0 { + return nil + } + extra := make(map[string]any, len(v)) + for key, value := range v { + switch key { + case "Context", "Gender", "Location", "Formality": + continue + default: + extra[key] = value + } + } + if len(extra) == 0 { + return nil + } + return extra + default: return nil } - return ctx.Extra } func (s *Service) getEffectiveFormality(data any) Formality { diff --git a/service_test.go b/service_test.go index 47df379..250fd4c 100644 --- a/service_test.go +++ b/service_test.go @@ -349,6 +349,31 @@ func TestServiceTranslationContextExtrasInLookup(t *testing.T) { } } +func TestServiceMapContextExtrasInLookup(t *testing.T) { + svc, err := New() + if err != nil { + t.Fatalf("New() failed: %v", err) + } + + svc.AddMessages("en", map[string]string{ + "welcome._greeting": "hello", + "welcome._greeting._region._europe": "bonjour", + "welcome._greeting._region._americas": "howdy", + }) + + if got := svc.T("welcome", map[string]any{"Context": "greeting"}); got != "hello" { + t.Errorf("T(welcome, map[Context:greeting]) = %q, want %q", got, "hello") + } + + if got := svc.T("welcome", map[string]any{"Context": "greeting", "region": "europe"}); got != "bonjour" { + t.Errorf("T(welcome, map[Context:greeting region:europe]) = %q, want %q", got, "bonjour") + } + + if got := svc.T("welcome", map[string]any{"Context": "greeting", "region": "americas"}); got != "howdy" { + t.Errorf("T(welcome, map[Context:greeting region:americas]) = %q, want %q", got, "howdy") + } +} + func TestServiceDefaultLocationAppliesToMapData(t *testing.T) { svc, err := New() if err != nil {