Adding support to customize helm template funcs

Signed-off-by: alexwo <alexwo@gmail.com>
pull/12135/head
i071873 2 years ago committed by alexwo
parent 1c4885fce7
commit 5151c3e4bd

@ -44,6 +44,11 @@ type Engine struct {
config *rest.Config
// EnableDNS tells the engine to allow DNS lookups when rendering templates
EnableDNS bool
// WithCustomFuncs allows you to provide a template.FuncMap containing custom template functions to be added or
// overridden. It is typically used as a configuration option to extend the default set of template functions with
// custom ones. The provided template.FuncMap can extend the default template functions, and the resulting
// FuncMap is used by the template engine.
WithCustomFuncs func(funcs template.FuncMap) template.FuncMap
}
// New creates a new instance of Engine using the passed in rest config.
@ -206,6 +211,10 @@ func (e Engine) initFunMap(t *template.Template, referenceTpls map[string]render
}
}
if e.WithCustomFuncs != nil {
funcMap = e.WithCustomFuncs(funcMap)
}
t.Funcs(funcMap)
}

@ -22,6 +22,7 @@ import (
"strings"
"sync"
"testing"
"text/template"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/chartutil"
@ -727,6 +728,44 @@ func TestAlterFuncMap_require(t *testing.T) {
}
}
func TestWithCustomFuncMap_tpl(t *testing.T) {
c := &chart.Chart{
Metadata: &chart.Metadata{Name: "TplFunction"},
Templates: []*chart.File{
{Name: "templates/base", Data: []byte(`Evaluate tpl {{tpl "Value: {{ .Values.value | custom }}" .}}`)},
},
}
v := chartutil.Values{
"Values": chartutil.Values{
"value": "myvalue",
},
"Chart": c.Metadata,
"Release": chartutil.Values{
"Name": "TestRelease",
},
}
e := Engine{
WithCustomFuncs: func(funcs template.FuncMap) template.FuncMap {
funcs["custom"] = func(name string) string {
return fmt.Sprintf("%s-from-custom-func", name)
}
return funcs
},
}
out, err := e.Render(c, v)
if err != nil {
t.Fatal(err)
}
expect := "Evaluate tpl Value: myvalue-from-custom-func"
if got := out["TplFunction/templates/base"]; got != expect {
t.Errorf("Expected %q, got %q (%v)", expect, got, out)
}
}
func TestAlterFuncMap_tpl(t *testing.T) {
c := &chart.Chart{
Metadata: &chart.Metadata{Name: "TplFunction"},

Loading…
Cancel
Save