From e8d2a7f7e7d6761995f4e0ed4e266733bc989670 Mon Sep 17 00:00:00 2001 From: Virgil Date: Fri, 3 Apr 2026 18:08:04 +0000 Subject: [PATCH] fix(html): normalise zero-value context defaults Co-Authored-By: Virgil --- context.go | 13 +++++++++++++ node_test.go | 12 ++++++++++++ 2 files changed, 25 insertions(+) diff --git a/context.go b/context.go index 2807b40..d0864be 100644 --- a/context.go +++ b/context.go @@ -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 diff --git a/node_test.go b/node_test.go index cab1f1a..19b90a4 100644 --- a/node_test.go +++ b/node_test.go @@ -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"))