diff --git a/i18n.go b/i18n.go index 63254cd..3b41175 100644 --- a/i18n.go +++ b/i18n.go @@ -112,6 +112,7 @@ func applyTemplate(text string, data any) string { if !core.Contains(text, "{{") { return text } + data = templateDataForRendering(data) if cached, ok := templateCache.Load(text); ok { var buf bytes.Buffer if err := cached.(*template.Template).Execute(&buf, data); err != nil { @@ -130,3 +131,41 @@ func applyTemplate(text string, data any) string { } return buf.String() } + +func templateDataForRendering(data any) any { + switch v := data.(type) { + case *TranslationContext: + if v == nil { + return nil + } + rendered := map[string]any{ + "Context": v.Context, + "Gender": v.Gender, + "Formality": v.Formality, + "Extra": v.Extra, + } + for key, value := range v.Extra { + if _, exists := rendered[key]; !exists { + rendered[key] = value + } + } + return rendered + case *Subject: + if v == nil { + return nil + } + return map[string]any{ + "Subject": v.String(), + "Noun": v.Noun, + "Count": v.count, + "Gender": v.gender, + "Location": v.location, + "Formality": v.formality, + "IsFormal": v.formality == FormalityFormal, + "IsPlural": v.count != 1, + "Value": v.Value, + } + default: + return data + } +} diff --git a/service_test.go b/service_test.go index ae12a5c..3dc5f71 100644 --- a/service_test.go +++ b/service_test.go @@ -247,6 +247,26 @@ func TestServiceTranslationContext(t *testing.T) { } } +func TestServiceTranslationContextExtrasInTemplates(t *testing.T) { + svc, err := New() + if err != nil { + t.Fatalf("New() failed: %v", err) + } + + svc.AddMessages("en", map[string]string{ + "welcome": "Hello {{.name}} from {{.Context}} in {{.city}}", + }) + + ctx := C("greeting"). + Set("name", "World"). + Set("city", "Paris") + + got := svc.T("welcome", ctx) + if got != "Hello World from greeting in Paris" { + t.Errorf("T(welcome, ctx) = %q, want %q", got, "Hello World from greeting in Paris") + } +} + func TestServiceDirection(t *testing.T) { svc, err := New() if err != nil {