forked from chanzuckerberg/fogg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
37 lines (33 loc) · 902 Bytes
/
template.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package util
import (
"io"
"io/ioutil"
"reflect"
"text/template"
"github.com/Masterminds/sprig"
"github.com/chanzuckerberg/fogg/errs"
log "github.com/sirupsen/logrus"
)
func dict(in interface{}) map[string]interface{} {
v := reflect.ValueOf(in)
if v.Kind() == reflect.Map {
r := make(map[string]interface{})
for _, key := range v.MapKeys() {
strct := v.MapIndex(key)
log.Debug(key.Interface(), strct.Interface())
r[key.String()] = strct.Interface()
}
return r
}
return nil
}
// OpenTemplate will read `source` for a template, parse, configure and return a template.Template
func OpenTemplate(source io.Reader) (*template.Template, error) {
s, err := ioutil.ReadAll(source)
if err != nil {
return nil, errs.WrapInternal(err, "could not read template")
}
funcs := sprig.TxtFuncMap()
funcs["dict"] = dict
return template.New("tmpl").Funcs(funcs).Parse(string(s))
}