fix(html): normalise zero-value context defaults
Co-Authored-By: Virgil <virgil@lethean.io>
This commit is contained in:
parent
ae286563fd
commit
e8d2a7f7e7
2 changed files with 25 additions and 0 deletions
13
context.go
13
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
|
||||
|
|
|
|||
12
node_test.go
12
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"))
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue