diff --git a/context.go b/context.go index c879fd6..8735bc5 100644 --- a/context.go +++ b/context.go @@ -20,18 +20,21 @@ type Context struct { } // NewContext creates a new rendering context with sensible defaults. -// Usage example: html := Render(Text("welcome"), NewContext()) -func NewContext() *Context { - return &Context{ +// Usage example: html := Render(Text("welcome"), NewContext("en-GB")) +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 translator. -// Usage example: ctx := NewContextWithService(myTranslator) -func NewContextWithService(svc Translator) *Context { - return &Context{ - Data: make(map[string]any), - service: svc, - } +// Usage example: ctx := NewContextWithService(myTranslator, "en-GB") +func NewContextWithService(svc Translator, locale ...string) *Context { + ctx := NewContext(locale...) + ctx.service = svc + return ctx } diff --git a/context_test.go b/context_test.go new file mode 100644 index 0000000..a9bedea --- /dev/null +++ b/context_test.go @@ -0,0 +1,38 @@ +// SPDX-Licence-Identifier: EUPL-1.2 + +package html + +import ( + "testing" + + i18n "dappco.re/go/core/i18n" +) + +func TestNewContext_OptionalLocale_Good(t *testing.T) { + ctx := NewContext("en-GB") + + if ctx == nil { + t.Fatal("NewContext returned nil") + } + if ctx.Locale != "en-GB" { + t.Fatalf("NewContext locale = %q, want %q", ctx.Locale, "en-GB") + } + if ctx.Data == nil { + t.Fatal("NewContext should initialise Data") + } +} + +func TestNewContextWithService_OptionalLocale_Good(t *testing.T) { + svc, _ := i18n.New() + ctx := NewContextWithService(svc, "fr-FR") + + if ctx == nil { + t.Fatal("NewContextWithService returned nil") + } + if ctx.Locale != "fr-FR" { + t.Fatalf("NewContextWithService locale = %q, want %q", ctx.Locale, "fr-FR") + } + if ctx.service == nil { + t.Fatal("NewContextWithService should set translator service") + } +}