From 0c19ccf7cc53c70c9663b08dc64a9a681aa13281 Mon Sep 17 00:00:00 2001 From: Snider Date: Wed, 15 Apr 2026 00:29:05 +0100 Subject: [PATCH] fix(html): honour Metadata alias for text counts Text() count/pluralisation now reads from either Context.Data or Context.Metadata, matching the alias contract when callers populate only one field.\n\nCo-Authored-By: Virgil --- context_test.go | 14 ++++++++++++++ text_translate_default.go | 21 ++++++++++++++++++--- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/context_test.go b/context_test.go index 93519d4..da36590 100644 --- a/context_test.go +++ b/context_test.go @@ -47,6 +47,20 @@ func TestNewContextWithService_AppliesLocaleToService_Good(t *testing.T) { } } +func TestTextNode_UsesMetadataAliasWhenDataNil_Good(t *testing.T) { + svc, _ := i18n.New() + i18n.SetDefault(svc) + + ctx := &Context{ + Metadata: map[string]any{"count": 1}, + } + + got := Text("i18n.count.file").Render(ctx) + if got != "1 file" { + t.Fatalf("Text with metadata-only count = %q, want %q", got, "1 file") + } +} + func TestContext_SetService_AppliesLocale_Good(t *testing.T) { svc, _ := i18n.New() ctx := NewContext("fr-FR") diff --git a/text_translate_default.go b/text_translate_default.go index 0ad60ce..90fa36e 100644 --- a/text_translate_default.go +++ b/text_translate_default.go @@ -12,11 +12,11 @@ import ( ) func translationArgs(ctx *Context, key string, args []any) []any { - if ctx == nil || len(ctx.Data) == 0 { + if ctx == nil { return args } - count, ok := contextCount(ctx.Data) + count, ok := contextCount(ctx) if !ok { return args } @@ -30,10 +30,25 @@ func translationArgs(ctx *Context, key string, args []any) []any { return args } -func contextCount(data map[string]any) (int, bool) { +func contextCount(ctx *Context) (int, bool) { + if ctx == nil { + return 0, false + } + + if n, ok := contextCountMap(ctx.Data); ok { + return n, true + } + if n, ok := contextCountMap(ctx.Metadata); ok { + return n, true + } + return 0, false +} + +func contextCountMap(data map[string]any) (int, bool) { if len(data) == 0 { return 0, false } + if v, ok := data["Count"]; ok { if n, ok := countInt(v); ok { return n, true