diff --git a/i18n.go b/i18n.go index 810ea25..5c1815e 100644 --- a/i18n.go +++ b/i18n.go @@ -2,6 +2,7 @@ package i18n import ( "bytes" + "io/fs" "strings" "text/template" @@ -171,6 +172,20 @@ func AddHandler(handlers ...KeyHandler) { } } +// LoadFS loads additional translations from an fs.FS into the default service. +// +// Call this from init() in packages that ship their own locale files: +// +// //go:embed locales/*.json +// var localeFS embed.FS +// +// func init() { i18n.LoadFS(localeFS, "locales") } +func LoadFS(fsys fs.FS, dir string) { + if svc := Default(); svc != nil { + _ = svc.LoadFS(fsys, dir) + } +} + // PrependHandler inserts one or more handlers at the start of the default service's handler chain. func PrependHandler(handlers ...KeyHandler) { if svc := Default(); svc != nil { diff --git a/i18n_test.go b/i18n_test.go index 14debce..73f769f 100644 --- a/i18n_test.go +++ b/i18n_test.go @@ -2,6 +2,7 @@ package i18n import ( "testing" + "testing/fstest" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -86,6 +87,27 @@ func TestRaw_Good_BypassesHandlers(t *testing.T) { assert.Equal(t, "i18n.label.status", got) } +func TestLoadFS_Good(t *testing.T) { + svc, err := New() + require.NoError(t, err) + prev := Default() + SetDefault(svc) + t.Cleanup(func() { + SetDefault(prev) + }) + + fsys := fstest.MapFS{ + "locales/en.json": &fstest.MapFile{ + Data: []byte(`{"loadfs.key": "loaded via package helper"}`), + }, + } + + LoadFS(fsys, "locales") + + got := T("loadfs.key") + assert.Equal(t, "loaded via package helper", got) +} + // --- SetLanguage / CurrentLanguage --- func TestSetLanguage_Good(t *testing.T) {