diff --git a/context.go b/context.go index 3bc77ef..a2eef2f 100644 --- a/context.go +++ b/context.go @@ -12,16 +12,26 @@ type Context struct { } // NewContext creates a new rendering context with sensible defaults. -func NewContext() *Context { - return &Context{ +// An optional locale may be provided as the first argument. +func NewContext(locale ...string) *Context { + ctx := &Context{ Data: make(map[string]any), } + if len(locale) > 0 { + ctx.Locale = locale[0] + } + return ctx } // NewContextWithService creates a rendering context backed by a specific i18n service. -func NewContextWithService(svc *i18n.Service) *Context { - return &Context{ +// An optional locale may be provided as the second argument. +func NewContextWithService(svc *i18n.Service, locale ...string) *Context { + ctx := &Context{ Data: make(map[string]any), service: svc, } + if len(locale) > 0 { + ctx.Locale = locale[0] + } + return ctx } diff --git a/node_test.go b/node_test.go index f55b5d7..a8c8335 100644 --- a/node_test.go +++ b/node_test.go @@ -16,6 +16,37 @@ func TestRawNode_Render(t *testing.T) { } } +func TestNewContext_Defaults(t *testing.T) { + ctx := NewContext() + if ctx == nil { + t.Fatal("NewContext() returned nil") + } + if ctx.Locale != "" { + t.Errorf("NewContext() Locale = %q, want empty string", ctx.Locale) + } + if ctx.Data == nil { + t.Fatal("NewContext() should initialise Data map") + } +} + +func TestNewContext_Locale(t *testing.T) { + ctx := NewContext("en-GB") + if ctx.Locale != "en-GB" { + t.Errorf("NewContext(locale) Locale = %q, want %q", ctx.Locale, "en-GB") + } +} + +func TestNewContextWithService_Locale(t *testing.T) { + svc, _ := i18n.New() + ctx := NewContextWithService(svc, "fr-FR") + if ctx.Locale != "fr-FR" { + t.Errorf("NewContextWithService(locale) Locale = %q, want %q", ctx.Locale, "fr-FR") + } + if ctx.service != svc { + t.Error("NewContextWithService should retain the provided service") + } +} + func TestElNode_Render(t *testing.T) { ctx := NewContext() node := El("div", Raw("content"))