-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
template.go
46 lines (38 loc) · 1.02 KB
/
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
38
39
40
41
42
43
44
45
46
package template
import (
"bytes"
"io"
"github.com/valyala/fasttemplate"
exprenv "github.com/argoproj/argo-workflows/v3/util/expr/env"
)
const (
prefix = "{{"
suffix = "}}"
)
type Template interface {
Replace(replaceMap map[string]string, allowUnresolved bool) (string, error)
}
func NewTemplate(s string) (Template, error) {
template, err := fasttemplate.NewTemplate(s, prefix, suffix)
if err != nil {
return nil, err
}
return &impl{template}, nil
}
type impl struct {
*fasttemplate.Template
}
func (t *impl) Replace(replaceMap map[string]string, allowUnresolved bool) (string, error) {
replacedTmpl := &bytes.Buffer{}
_, err := t.Template.ExecuteFunc(replacedTmpl, func(w io.Writer, tag string) (int, error) {
kind, expression := parseTag(tag)
switch kind {
case kindExpression:
env := exprenv.GetFuncMap(EnvMap(replaceMap))
return expressionReplace(w, expression, env, allowUnresolved)
default:
return simpleReplace(w, tag, replaceMap, allowUnresolved)
}
})
return replacedTmpl.String(), err
}