From 94191ce3b45a9fe8a8dc232d7d6e5ae0a7422426 Mon Sep 17 00:00:00 2001 From: Richard Kosegi Date: Tue, 6 Aug 2024 11:13:07 +0200 Subject: [PATCH] Pipeline: Add 'tpl' template function Signed-off-by: Richard Kosegi --- pipeline/template_engine.go | 17 +++++++++++++++++ pipeline/template_engine_test.go | 23 +++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/pipeline/template_engine.go b/pipeline/template_engine.go index 1d96f30..f1a1991 100644 --- a/pipeline/template_engine.go +++ b/pipeline/template_engine.go @@ -27,8 +27,25 @@ type templateEngine struct { fm template.FuncMap } +func tplFunc(tmpl *template.Template) func(string, interface{}) (string, error) { + return func(tpl string, data interface{}) (string, error) { + t, _ := tmpl.Clone() + t, err := tmpl.New(tmpl.Name()).Parse(tpl) + if err != nil { + return "", err + } + var buf strings.Builder + err = t.Execute(&buf, data) + return buf.String(), 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), + }) + 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 6ad70d4..da841b9 100644 --- a/pipeline/template_engine_test.go +++ b/pipeline/template_engine_test.go @@ -61,3 +61,26 @@ func TestRenderTemplate(t *testing.T) { _, err = renderTemplate("{{ .a }}", "", sprig.TxtFuncMap()) assert.Error(t, err) } + +func TestTemplateEngineRenderTpl(t *testing.T) { + var ( + out string + err error + ) + out, err = renderTemplate("{{ tpl .T . }}", map[string]interface{}{ + "T": "{{ add .X 3 }}", + "X": 10, + }, sprig.TxtFuncMap()) + assert.NoError(t, err) + assert.Equal(t, "13", out) +} + +func TestTemplateEngineRenderTplInvalid(t *testing.T) { + var ( + err error + ) + _, err = renderTemplate("{{ tpl .T . }}", map[string]interface{}{ + "T": "{{", + }, sprig.TxtFuncMap()) + assert.Error(t, err) +}