tpl: Extend Jsonify to support optional indent parameter

Fixes #5040
This commit is contained in:
Cameron Moore 2020-03-21 10:15:12 -05:00 committed by Bjørn Erik Pedersen
parent 7eba37ae9b
commit 1bc93021e3
3 changed files with 38 additions and 9 deletions

View file

@ -17,6 +17,7 @@ package encoding
import ( import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"errors"
"html/template" "html/template"
"github.com/spf13/cast" "github.com/spf13/cast"
@ -51,9 +52,32 @@ func (ns *Namespace) Base64Encode(content interface{}) (string, error) {
return base64.StdEncoding.EncodeToString([]byte(conv)), nil return base64.StdEncoding.EncodeToString([]byte(conv)), nil
} }
// Jsonify encodes a given object to JSON. // Jsonify encodes a given object to JSON. To pretty print the JSON, pass an
func (ns *Namespace) Jsonify(v interface{}) (template.HTML, error) { // optional first argument of the indent string, such as " ".
b, err := json.Marshal(v) func (ns *Namespace) Jsonify(args ...interface{}) (template.HTML, error) {
var (
b []byte
err error
)
switch len(args) {
case 0:
return "", nil
case 1:
b, err = json.Marshal(args[0])
case 2:
var indent string
indent, err = cast.ToStringE(args[0])
if err != nil {
break
}
b, err = json.MarshalIndent(args[1], "", indent)
default:
err = errors.New("too many arguments to jsonify")
}
if err != nil { if err != nil {
return "", err return "", err
} }

View file

@ -83,17 +83,22 @@ func TestJsonify(t *testing.T) {
ns := New() ns := New()
for _, test := range []struct { for _, test := range []struct {
indent []interface{}
v interface{} v interface{}
expect interface{} expect interface{}
}{ }{
{[]string{"a", "b"}, template.HTML(`["a","b"]`)}, {nil, []string{"a", "b"}, template.HTML(`["a","b"]`)},
{tstNoStringer{}, template.HTML("{}")}, {[]interface{}{" "}, []string{"a", "b"}, template.HTML("[\n \"a\",\n \"b\"\n]")},
{nil, template.HTML("null")}, {nil, tstNoStringer{}, template.HTML("{}")},
{nil, nil, template.HTML("null")},
// errors // errors
{math.NaN(), false}, {nil, math.NaN(), false},
{[]interface{}{tstNoStringer{}}, []string{"a", "b"}, false},
} { } {
result, err := ns.Jsonify(test.v) args := append(test.indent, test.v)
result, err := ns.Jsonify(args...)
if b, ok := test.expect.(bool); ok && !b { if b, ok := test.expect.(bool); ok && !b {
c.Assert(err, qt.Not(qt.IsNil)) c.Assert(err, qt.Not(qt.IsNil))

View file

@ -48,11 +48,11 @@ func init() {
[]string{"jsonify"}, []string{"jsonify"},
[][2]string{ [][2]string{
{`{{ (slice "A" "B" "C") | jsonify }}`, `["A","B","C"]`}, {`{{ (slice "A" "B" "C") | jsonify }}`, `["A","B","C"]`},
{`{{ (slice "A" "B" "C") | jsonify " "}}`, "[\n \"A\",\n \"B\",\n \"C\"\n]"},
}, },
) )
return ns return ns
} }
internal.AddTemplateFuncsNamespace(f) internal.AddTemplateFuncsNamespace(f)