diff --git a/pkg/engine/engine.go b/pkg/engine/engine.go index ba1fa9681..e9fda7f6e 100644 --- a/pkg/engine/engine.go +++ b/pkg/engine/engine.go @@ -122,29 +122,29 @@ func includeFun(t *template.Template, includedNames map[string]int) func(string, } } -// initFunMap creates the Engine's FuncMap and adds context-specific functions. -func (e Engine) initFunMap(t *template.Template) { - funcMap := funcMap() - includedNames := make(map[string]int) - - // Add the 'include' function here so we can close over t. - funcMap["include"] = includeFun(t, includedNames) - - // Add the 'tpl' function here - funcMap["tpl"] = func(tpl string, vals chartutil.Values) (string, error) { - t, err := t.Clone() +// As does 'tpl', so that nested calls to 'tpl' see the templates +// defined by their enclosing contexts. +func tplFun(parent *template.Template, includedNames map[string]int) func(string, interface{}) (string, error) { + return func(tpl string, vals interface{}) (string, error) { + t, err := parent.Clone() if err != nil { return "", errors.Wrapf(err, "cannot clone template") } // Re-inject 'include' so that it can close over our clone of t; // this lets any 'define's inside tpl be 'include'd. - tplFuncMap := template.FuncMap{ + t.Funcs(template.FuncMap{ "include": includeFun(t, includedNames), - } - t.Funcs(tplFuncMap) - - t, err = t.Parse(tpl) + "tpl": tplFun(t, includedNames), + }) + + // We need a .New template, as template text which is just blanks + // or comments after parsing out defines just addes new named + // template definitions without changing the main template. + // https://pkg.go.dev/text/template#Template.Parse + // Use the parent's name for lack of a better way to identify the tpl + // text string. (Maybe we could use a hash appended to the name?) + t, err = t.New(parent.Name()).Parse(tpl) if err != nil { return "", errors.Wrapf(err, "cannot parse template %q", tpl) } @@ -154,9 +154,19 @@ func (e Engine) initFunMap(t *template.Template) { return "", errors.Wrapf(err, "error during tpl function execution for %q", tpl) } - // See comment in render explaining the hack. + // See comment in renderWithReferences explaining the hack. return strings.ReplaceAll(buf.String(), "", ""), nil } +} + +// initFunMap creates the Engine's FuncMap and adds context-specific functions. +func (e Engine) initFunMap(t *template.Template) { + funcMap := funcMap() + includedNames := make(map[string]int) + + // Add the template-rendering functions here so we can close over t. + funcMap["include"] = includeFun(t, includedNames) + funcMap["tpl"] = tplFun(t, includedNames) // Add the `required` function here so we can use lintMode funcMap["required"] = func(warn string, val interface{}) (interface{}, error) {