feat(context): accept optional locale
Allow callers to seed Locale directly when constructing a rendering context, while preserving the existing no-argument API. Co-Authored-By: Virgil <virgil@lethean.io>
This commit is contained in:
parent
149d31b140
commit
84ad59cd09
2 changed files with 45 additions and 4 deletions
18
context.go
18
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
|
||||
}
|
||||
|
|
|
|||
31
node_test.go
31
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"))
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue