fix(html): normalise zero-value context defaults
Some checks are pending
Security Scan / security (push) Waiting to run
Test / test (push) Waiting to run

Co-Authored-By: Virgil <virgil@lethean.io>
This commit is contained in:
Virgil 2026-04-03 18:08:04 +00:00
parent ae286563fd
commit e8d2a7f7e7
2 changed files with 25 additions and 0 deletions

View file

@ -33,10 +33,21 @@ func applyLocaleToService(svc Translator, locale string) {
}
}
// ensureContextDefaults initialises lazily-created context fields.
func ensureContextDefaults(ctx *Context) {
if ctx == nil {
return
}
if ctx.Data == nil {
ctx.Data = make(map[string]any)
}
}
// normaliseContext ensures render paths always have a usable context.
// A nil input is replaced with a fresh default context.
func normaliseContext(ctx *Context) *Context {
if ctx != nil {
ensureContextDefaults(ctx)
return ctx
}
return NewContext()
@ -71,6 +82,7 @@ func (ctx *Context) SetService(svc Translator) *Context {
return nil
}
ensureContextDefaults(ctx)
ctx.service = svc
applyLocaleToService(svc, ctx.Locale)
return ctx
@ -83,6 +95,7 @@ func (ctx *Context) SetLocale(locale string) *Context {
return nil
}
ensureContextDefaults(ctx)
ctx.Locale = locale
applyLocaleToService(ctx.service, ctx.Locale)
return ctx

View file

@ -48,6 +48,18 @@ func TestNewContextWithService_Locale(t *testing.T) {
}
}
func TestRender_NormalisesZeroValueContext(t *testing.T) {
ctx := &Context{}
got := Text("hello").Render(ctx)
if got != "hello" {
t.Fatalf("Text(\"hello\").Render(&Context{}) = %q, want %q", got, "hello")
}
if ctx.Data == nil {
t.Fatal("Render should initialise Data on a zero-value context")
}
}
func TestElNode_Render(t *testing.T) {
ctx := NewContext()
node := El("div", Raw("content"))