Allow a nested `tpl` invocation access to `defines` in a containing one

Signed-off-by: Graham Reed <greed@7deadly.org>
pull/11351/head
Graham Reed 2 years ago
parent e2a7c7998a
commit a7d3fd6c09

@ -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 <no value> hack.
// See comment in renderWithReferences explaining the <no value> hack.
return strings.ReplaceAll(buf.String(), "<no value>", ""), 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) {

Loading…
Cancel
Save