From 2c98c593442eaf3fb6ca7d70d9feb569a887cfd1 Mon Sep 17 00:00:00 2001 From: Demian Date: Mon, 5 Aug 2024 00:23:01 +0200 Subject: [PATCH] layout: implement nested locales --- layout/layout_test.go | 13 +++++++++++++ layout/locales/en.yml | 9 ++++++++- layout/parser.go | 13 +++++++++---- 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/layout/layout_test.go b/layout/layout_test.go index bc11ef3..2192222 100644 --- a/layout/layout_test.go +++ b/layout/layout_test.go @@ -132,4 +132,17 @@ func TestLayout(t *testing.T) { Description: "Some description", PreviewURL: "https://preview.picture", })) + + assert.Equal(t, + "This is an article.", + lt.TextLocale("en", "article_message"), + ) + assert.Equal(t, + lt.TextLocale("en", "nested.example", "an example"), + "This is an example.", + ) + assert.Equal(t, + lt.TextLocale("en", "nested.another.example", "another example"), + "This is another example.", + ) } diff --git a/layout/locales/en.yml b/layout/locales/en.yml index e3bfee9..21f0b5c 100644 --- a/layout/locales/en.yml +++ b/layout/locales/en.yml @@ -1 +1,8 @@ -article_message: This is an article. \ No newline at end of file +article_message: This is an article. + +nested: + example: |- + This is {{ . }}. + another: + example: |- + This is {{ . }}. diff --git a/layout/parser.go b/layout/parser.go index 6f0a659..f973e1d 100644 --- a/layout/parser.go +++ b/layout/parser.go @@ -246,18 +246,23 @@ func (lt *Layout) parseLocales(dir string) error { return err } - var texts map[string]string + var texts map[string]interface{} if err := yaml.Unmarshal(data, &texts); err != nil { return err } + v := viper.New() + if err := v.MergeConfigMap(texts); err != nil { + return err + } + name := fi.Name() name = strings.TrimSuffix(name, filepath.Ext(name)) tmpl := template.New(name).Funcs(lt.funcs) - for key, text := range texts { - _, err = tmpl.New(key).Parse(strings.Trim(text, "\r\n")) - if err != nil { + for _, key := range v.AllKeys() { + text := strings.Trim(v.GetString(key), "\r\n") + if _, err := tmpl.New(key).Parse(text); err != nil { return err } }