pull/31950/merge
Ali Pourrahim 3 days ago committed by GitHub
commit fac933318a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -83,7 +83,7 @@ func TestFuncMap(t *testing.T) {
}
// Test for Engine-specific template functions.
expect := []string{"include", "required", "tpl", "toYaml", "fromYaml", "toToml", "fromToml", "toJson", "fromJson", "lookup"}
expect := []string{"include", "required", "tpl", "toYaml", "fromYaml", "toToml", "mustToToml", "fromToml", "toJson", "fromJson", "lookup"}
for _, f := range expect {
if _, ok := fns[f]; !ok {
t.Errorf("Expected add-on function %q", f)

@ -50,6 +50,7 @@ func funcMap() template.FuncMap {
// Add some extra functionality
extra := template.FuncMap{
"toToml": toTOML,
"mustToToml": mustToTOML,
"fromToml": fromTOML,
"toYaml": toYAML,
"mustToYaml": mustToYAML,
@ -157,7 +158,23 @@ func toTOML(v any) string {
e := toml.NewEncoder(b)
err := e.Encode(v)
if err != nil {
return err.Error()
// Swallow errors inside of a template.
return ""
}
return b.String()
}
// mustToTOML takes an interface, marshals it to toml, and returns a string.
// It will panic if there is an error.
//
// This is designed to be called from a template when need to ensure that the
// output TOML is valid.
func mustToTOML(v any) string {
b := bytes.NewBuffer(nil)
e := toml.NewEncoder(b)
err := e.Encode(v)
if err != nil {
panic(err)
}
return b.String()
}

@ -151,6 +151,9 @@ keyInElement1 = "valueInElement1"`,
}, {
tpl: `{{ mustToJson . }}`,
vars: loopMap,
}, {
tpl: `{{ mustToToml . }}`,
vars: loopMap,
}, {
tpl: `{{ toYaml . }}`,
expect: "", // should return empty string and swallow error
@ -159,6 +162,10 @@ keyInElement1 = "valueInElement1"`,
tpl: `{{ toJson . }}`,
expect: "", // should return empty string and swallow error
vars: loopMap,
}, {
tpl: `{{ toToml . }}`,
expect: "", // should return empty string and swallow error
vars: loopMap,
},
}

Loading…
Cancel
Save