adding toJsonPretty function variant of toJson

toJsonPretty is mostly a copy of toJson, but instead of
  `json.Marshal` is using `json.MarshalIndent` to pretty
  print JSON

Signed-off-by: Anastas Dancha <anapsix@random.io>
pull/8230/head
Anastas Dancha 5 years ago
parent 03ccd5dea2
commit 4160749018

@ -70,7 +70,7 @@ func TestFuncMap(t *testing.T) {
}
// Test for Engine-specific template functions.
expect := []string{"include", "required", "tpl", "toYaml", "fromYaml", "toToml", "toJson", "fromJson", "lookup"}
expect := []string{"include", "required", "tpl", "toYaml", "fromYaml", "toToml", "toJson", "toJsonPretty", "fromJson", "lookup"}
for _, f := range expect {
if _, ok := fns[f]; !ok {
t.Errorf("Expected add-on function %q", f)
@ -89,6 +89,7 @@ func TestRender(t *testing.T) {
{Name: "templates/test2", Data: []byte("{{.Values.global.callme | lower }}")},
{Name: "templates/test3", Data: []byte("{{.noValue}}")},
{Name: "templates/test4", Data: []byte("{{toJson .Values}}")},
{Name: "templates/test5", Data: []byte("{{toJsonPretty .Values}}")},
},
Values: map[string]interface{}{"outer": "DEFAULT", "inner": "DEFAULT"},
}

@ -53,6 +53,7 @@ func funcMap() template.FuncMap {
"fromYaml": fromYAML,
"fromYamlArray": fromYAMLArray,
"toJson": toJSON,
"toJsonPretty": toJSONPretty,
"fromJson": fromJSON,
"fromJsonArray": fromJSONArray,
@ -146,6 +147,20 @@ func toJSON(v interface{}) string {
return string(data)
}
// toJSONPretty takes an interface, marshals it to json (with indent of two
// spaces, and returns a string. It will always return a string, even on marshal
// error (empty string).
//
// This is designed to be called from a template.
func toJSONPretty(v interface{}) string {
data, err := json.MarshalIndent(v, "", " ")
if err != nil {
// Swallow errors inside of a template.
return ""
}
return string(data)
}
// fromJSON converts a JSON document into a map[string]interface{}.
//
// This is not a general-purpose JSON parser, and will not parse all valid

@ -41,6 +41,10 @@ func TestFuncs(t *testing.T) {
tpl: `{{ toJson . }}`,
expect: `{"foo":"bar"}`,
vars: map[string]interface{}{"foo": "bar"},
}, {}, {
tpl: `{{ toJsonPretty . }}`,
expect: "{\n \"foo\": \"bar\"\n}",
vars: map[string]interface{}{"foo": "bar"},
}, {
tpl: `{{ fromYaml . }}`,
expect: "map[hello:world]",

Loading…
Cancel
Save