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:
parent
efe49de57f
commit
25f2a1616c
1 changed files with 13 additions and 1 deletions
|
@ -2,6 +2,7 @@ package templater
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"os"
|
"os"
|
||||||
|
@ -9,6 +10,7 @@ import (
|
||||||
"strings"
|
"strings"
|
||||||
"text/template"
|
"text/template"
|
||||||
|
|
||||||
|
"github.com/Masterminds/sprig"
|
||||||
"github.com/polydawn/meep"
|
"github.com/polydawn/meep"
|
||||||
"github.com/tazjin/kontemplate/context"
|
"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) {
|
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 {
|
if err != nil {
|
||||||
return "", meep.New(
|
return "", meep.New(
|
||||||
|
@ -123,6 +125,16 @@ func templateFile(c *context.Context, rs *context.ResourceSet, filename string)
|
||||||
return b.String(), nil
|
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)
|
// Checks whether a file is a resource file (i.e. is YAML or JSON)
|
||||||
func isResourceFile(f os.FileInfo) bool {
|
func isResourceFile(f os.FileInfo) bool {
|
||||||
return strings.HasSuffix(f.Name(), "yaml") ||
|
return strings.HasSuffix(f.Name(), "yaml") ||
|
||||||
|
|
Loading…
Reference in a new issue