diff --git a/components/engine/pkg/templates/templates.go b/components/engine/pkg/templates/templates.go index 2ac44fad44..75a3dd974e 100644 --- a/components/engine/pkg/templates/templates.go +++ b/components/engine/pkg/templates/templates.go @@ -1,6 +1,7 @@ package templates import ( + "bytes" "encoding/json" "strings" "text/template" @@ -10,8 +11,12 @@ import ( // functions provided to every template. var basicFunctions = template.FuncMap{ "json": func(v interface{}) string { - a, _ := json.Marshal(v) - return string(a) + buf := &bytes.Buffer{} + enc := json.NewEncoder(buf) + enc.SetEscapeHTML(false) + enc.Encode(v) + // Remove the trailing new line added by the encoder + return strings.TrimSpace(buf.String()) }, "split": strings.Split, "join": strings.Join, diff --git a/components/engine/pkg/templates/templates_test.go b/components/engine/pkg/templates/templates_test.go index f972571912..7f14802454 100644 --- a/components/engine/pkg/templates/templates_test.go +++ b/components/engine/pkg/templates/templates_test.go @@ -7,6 +7,17 @@ import ( "github.com/stretchr/testify/assert" ) +// Github #32120 +func TestParseJSONFunctions(t *testing.T) { + tm, err := Parse(`{{json .Ports}}`) + assert.NoError(t, err) + + var b bytes.Buffer + assert.NoError(t, tm.Execute(&b, map[string]string{"Ports": "0.0.0.0:2->8/udp"})) + want := "\"0.0.0.0:2->8/udp\"" + assert.Equal(t, want, b.String()) +} + func TestParseStringFunctions(t *testing.T) { tm, err := Parse(`{{join (split . ":") "/"}}`) assert.NoError(t, err)