diff --git a/CHANGELOG.md b/CHANGELOG.md index f79df7327..55e8b06b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +## 0.2.10 (Unreleased) + +IMPOROVEMENTS: + * Add `toJSON` template helper + ## 0.2.9 (27 December 2019) IMPROVEMENTS: diff --git a/template/funcs.go b/template/funcs.go index 2d1659408..e937e275e 100644 --- a/template/funcs.go +++ b/template/funcs.go @@ -1,6 +1,7 @@ package template import ( + "bytes" "encoding/json" "errors" "fmt" @@ -35,6 +36,7 @@ func funcMap(consulClient *consul.Client) template.FuncMap { "timeNow": timeNowFunc, "timeNowUTC": timeNowUTCFunc, "timeNowTimezone": timeNowTimezoneFunc(), + "toJSON": toJSON, "toLower": toLower, "toUpper": toUpper, @@ -231,6 +233,15 @@ func timeNowTimezoneFunc() func(string) (string, error) { } } +// toJSON converts the given structure into a deeply nested JSON string. +func toJSON(i interface{}) (string, error) { + result, err := json.Marshal(i) + if err != nil { + return "", err + } + return string(bytes.TrimSpace(result)), err +} + func toLower(s string) (string, error) { return strings.ToLower(s), nil }