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
This commit is contained in:
Vincent Ambo 2017-02-08 14:37:36 +01:00
parent efe49de57f
commit 25f2a1616c

View file

@ -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") ||