about summary refs log tree commit diff
path: root/templater
diff options
context:
space:
mode:
authorVincent Ambo <tazjin@gmail.com>2017-02-08T13·37+0100
committerVincent Ambo <tazjin@gmail.com>2017-02-08T13·40+0100
commit25f2a1616caf2a05199370998223f4a64bb55f81 (patch)
tree18c0550396fa41dbf519aaa65efe980e67db24aa /templater
parentefe49de57f6757c7ae6752927029932c556e881c (diff)
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
Diffstat (limited to 'templater')
-rw-r--r--templater/templater.go14
1 files changed, 13 insertions, 1 deletions
diff --git a/templater/templater.go b/templater/templater.go
index 5c1db77aadfd..6e443c14bb07 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") ||