feat(i18n): render context extras in templates
All checks were successful
Security Scan / security (push) Successful in 10s
Test / test (push) Successful in 1m1s

Co-Authored-By: Virgil <virgil@lethean.io>
This commit is contained in:
Virgil 2026-04-01 08:47:09 +00:00
parent 87557b66e4
commit 71e0049622
2 changed files with 59 additions and 0 deletions

39
i18n.go
View file

@ -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
}
}

View file

@ -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 {