feat: `tpl` template function (#504)

Add `tpl` template function that looks exactly like helm's one.

Resolves #420
This commit is contained in:
KUOKA Yusuke 2019-03-25 18:08:47 +09:00 committed by GitHub
parent 056d150856
commit 0639714136
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 0 deletions

View File

@ -24,6 +24,7 @@ func (c *Context) createFuncMap() template.FuncMap {
"requiredEnv": RequiredEnv,
"get": get,
"getOrNil": getOrNil,
"tpl": c.Tpl,
}
if c.preRender {
// disable potential side-effect template calls
@ -128,6 +129,14 @@ func (c *Context) ReadFile(filename string) (string, error) {
return string(bytes), nil
}
func (c *Context) Tpl(text string, data interface{}) (string, error) {
buf, err := c.RenderTemplateToBuffer(text, data)
if err != nil {
return "", err
}
return buf.String(), nil
}
func ToYaml(v interface{}) (string, error) {
data, err := yaml.Marshal(v)
if err != nil {

View File

@ -118,3 +118,18 @@ func TestSetValueAtPath_TwoComponents(t *testing.T) {
t.Errorf("unexpected result: expected=%v, actual=%v", expected, actual)
}
}
func TestTpl(t *testing.T) {
text := `foo: {{ .foo }}
`
expected := `foo: FOO
`
ctx := &Context{basePath: "."}
actual, err := ctx.Tpl(text, map[string]interface{}{"foo": "FOO"})
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !reflect.DeepEqual(actual, expected) {
t.Errorf("unexpected result: expected=%v, actual=%v", expected, actual)
}
}