diff --git a/pipeline/template_engine.go b/pipeline/template_engine.go index f1a1991..f2cb320 100644 --- a/pipeline/template_engine.go +++ b/pipeline/template_engine.go @@ -18,6 +18,7 @@ package pipeline import ( "bytes" + "github.com/rkosegi/yaml-toolkit/utils" "strconv" "strings" "text/template" @@ -40,12 +41,18 @@ func tplFunc(tmpl *template.Template) func(string, interface{}) (string, error) } } +func toYamlFunc(v interface{}) (string, error) { + var buf strings.Builder + err := utils.NewYamlEncoder(&buf).Encode(v) + return strings.TrimSuffix(buf.String(), "\n"), err +} + func renderTemplate(tmplStr string, data interface{}, fm template.FuncMap) (string, error) { tmpl := template.New("tmpl").Funcs(fm) tmpl.Funcs(template.FuncMap{ - "tpl": tplFunc(tmpl), + "tpl": tplFunc(tmpl), + "toYaml": toYamlFunc, }) - tplFunc(tmpl) _, err := tmpl.Parse(tmplStr) if err != nil { return "", err diff --git a/pipeline/template_engine_test.go b/pipeline/template_engine_test.go index da841b9..4dc948c 100644 --- a/pipeline/template_engine_test.go +++ b/pipeline/template_engine_test.go @@ -84,3 +84,18 @@ func TestTemplateEngineRenderTplInvalid(t *testing.T) { }, sprig.TxtFuncMap()) assert.Error(t, err) } + +func TestTemplateEngineRenderToYaml(t *testing.T) { + var ( + out string + err error + ) + out, err = renderTemplate("{{ toYaml . }}", map[string]interface{}{ + "x": map[string]interface{}{ + "z": "abc", + }, + "y": 25, + }, sprig.TxtFuncMap()) + assert.NoError(t, err) + assert.Equal(t, "x:\n z: abc\n\"y\": 25", out) +}