feat(html): allow locale in context constructors
Co-Authored-By: Virgil <virgil@lethean.io>
This commit is contained in:
parent
4a3a69e8b7
commit
cb901dbb71
2 changed files with 50 additions and 9 deletions
21
context.go
21
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
|
||||
}
|
||||
|
|
|
|||
38
context_test.go
Normal file
38
context_test.go
Normal file
|
|
@ -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")
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue