From 2e2af31c1d24b583ebf97bde89d5638c5be51c57 Mon Sep 17 00:00:00 2001 From: Virgil Date: Tue, 31 Mar 2026 20:48:08 +0000 Subject: [PATCH] feat(html): add locale setter for context translators Co-Authored-By: Virgil --- context.go | 12 ++++++++++++ context_test.go | 21 +++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/context.go b/context.go index 1710b2f..5c1f61e 100644 --- a/context.go +++ b/context.go @@ -67,3 +67,15 @@ func (ctx *Context) SetService(svc Translator) *Context { applyLocaleToService(svc, ctx.Locale) return ctx } + +// SetLocale updates the context locale and reapplies it to the active translator. +// Usage example: ctx.SetLocale("en-GB") +func (ctx *Context) SetLocale(locale string) *Context { + if ctx == nil { + return nil + } + + ctx.Locale = locale + applyLocaleToService(ctx.service, ctx.Locale) + return ctx +} diff --git a/context_test.go b/context_test.go index 7c86db7..93519d4 100644 --- a/context_test.go +++ b/context_test.go @@ -67,3 +67,24 @@ func TestContext_SetService_NilContext_Ugly(t *testing.T) { t.Fatal("SetService on nil context should return nil") } } + +func TestContext_SetLocale_AppliesLocale_Good(t *testing.T) { + svc, _ := i18n.New() + ctx := NewContextWithService(svc) + + if got := ctx.SetLocale("fr-FR"); got != ctx { + t.Fatal("SetLocale should return the same context for chaining") + } + + got := Text("prompt.yes").Render(ctx) + if got != "o" { + t.Fatalf("SetLocale translation = %q, want %q", got, "o") + } +} + +func TestContext_SetLocale_NilContext_Ugly(t *testing.T) { + var ctx *Context + if got := ctx.SetLocale("en-GB"); got != nil { + t.Fatal("SetLocale on nil context should return nil") + } +}