From 25f2a1616caf2a05199370998223f4a64bb55f81 Mon Sep 17 00:00:00 2001 From: Vincent Ambo Date: Wed, 8 Feb 2017 14:37:36 +0100 Subject: [PATCH] feat template: Add additional template functions This adds the Go template functions from [sprig][] as well as a custom `json` function that can interpolate any data as a JSON object - very useful for adding arrays of data in JSON format into a variable: ``` certificateDomains: - oslo.pub - tazj.in annotations: acme/certificate: {{ .certificateDomains | json }} annotations: acme/certificate: ["oslo.pub", "tazj.in"] ``` [sprig]: https://godoc.org/github.com/Masterminds/sprig --- templater/templater.go | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/templater/templater.go b/templater/templater.go index 5c1db77aa..6e443c14b 100644 --- a/templater/templater.go +++ b/templater/templater.go @@ -2,6 +2,7 @@ package templater import ( "bytes" + "encoding/json" "fmt" "io/ioutil" "os" @@ -9,6 +10,7 @@ import ( "strings" "text/template" + "github.com/Masterminds/sprig" "github.com/polydawn/meep" "github.com/tazjin/kontemplate/context" ) @@ -88,7 +90,7 @@ func processFiles(c *context.Context, rs *context.ResourceSet, rp string, files } func templateFile(c *context.Context, rs *context.ResourceSet, filename string) (string, error) { - tpl, err := template.ParseFiles(filename) + tpl, err := template.New(path.Base(filename)).Funcs(templateFuncs()).ParseFiles(filename) if err != nil { return "", meep.New( @@ -123,6 +125,16 @@ func templateFile(c *context.Context, rs *context.ResourceSet, filename string) return b.String(), nil } +func templateFuncs() template.FuncMap { + m := sprig.TxtFuncMap() + m["json"] = func(data interface{}) string { + b, _ := json.Marshal(data) + return string(b) + } + + return m +} + // Checks whether a file is a resource file (i.e. is YAML or JSON) func isResourceFile(f os.FileInfo) bool { return strings.HasSuffix(f.Name(), "yaml") ||