Skip to content

Commit

Permalink
fix: option in TextParser is not used (#335)
Browse files Browse the repository at this point in the history
Resolves #334

---------

Signed-off-by: Stéphane Cazeaux <[email protected]>
Co-authored-by: Nick Snyder <[email protected]>
  • Loading branch information
cazeaux and nicksnyder authored Oct 12, 2024
1 parent 8f901db commit 1cb10df
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
32 changes: 31 additions & 1 deletion i18n/localizer_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package i18n

import (
"errors"
"fmt"
"reflect"
"testing"
gotmpl "text/template"

"github.com/nicksnyder/go-i18n/v2/i18n/template"
"github.com/nicksnyder/go-i18n/v2/internal/plural"
Expand Down Expand Up @@ -648,6 +650,34 @@ func localizerTests() []localizerTest {
},
expectedErr: &MessageNotFoundErr{Tag: language.English, MessageID: "Hello"},
},
{
name: "use option missingkey=error with missing key",
defaultLanguage: language.English,
messages: map[language.Tag][]*Message{
language.English: {{ID: "Foo", Other: "Foo {{.bar}}"}},
},
acceptLangs: []string{"en"},
conf: &LocalizeConfig{
MessageID: "Foo",
TemplateData: map[string]string{},
TemplateParser: &template.TextParser{Option: "missingkey=error"},
},
expectedErr: gotmpl.ExecError{Name: "", Err: errors.New(`template: :1:6: executing "" at <.bar>: map has no entry for key "bar"`)},
},
{
name: "use option missingkey=default with missing key",
defaultLanguage: language.English,
messages: map[language.Tag][]*Message{
language.English: {{ID: "Foo", Other: "Foo {{.bar}}"}},
},
acceptLangs: []string{"en"},
conf: &LocalizeConfig{
MessageID: "Foo",
TemplateData: map[string]string{},
TemplateParser: &template.TextParser{Option: "missingkey=default"},
},
expectedLocalized: "Foo <no value>",
},
}
}

Expand All @@ -663,7 +693,7 @@ func TestLocalizer_Localize(t *testing.T) {
check := func(localized string, err error) {
t.Helper()
if !reflect.DeepEqual(err, test.expectedErr) {
t.Errorf("expected error %#v; got %#v", test.expectedErr, err)
t.Errorf("\nexpected error: %#v\n got error: %#v", test.expectedErr, err)
}
if localized != test.expectedLocalized {
t.Errorf("expected localized string %q; got %q", test.expectedLocalized, localized)
Expand Down
7 changes: 6 additions & 1 deletion i18n/template/text_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,12 @@ func (te *TextParser) Parse(src, leftDelim, rightDelim string) (ParsedTemplate,
rightDelim = "}}"
}

tmpl, err := template.New("").Delims(leftDelim, rightDelim).Funcs(te.Funcs).Parse(src)
option := "missingkey=default"
if te.Option != "" {
option = te.Option
}

tmpl, err := template.New("").Delims(leftDelim, rightDelim).Option(option).Funcs(te.Funcs).Parse(src)
if err != nil {
return nil, err
}
Expand Down

0 comments on commit 1cb10df

Please sign in to comment.