Skip to content

Commit

Permalink
Work around template.Clone omitting options
Browse files Browse the repository at this point in the history
Signed-off-by: Graham Reed <greed@7deadly.org>
  • Loading branch information
greed42 committed May 11, 2023
1 parent a7d3fd6 commit 95905f1
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions pkg/engine/engine.go
Expand Up @@ -124,18 +124,27 @@ func includeFun(t *template.Template, includedNames map[string]int) func(string,

// 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) {
func tplFun(parent *template.Template, includedNames map[string]int, strict bool) 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 the missingkey option, see text/template issue https://github.com/golang/go/issues/43022
// We have to go by strict from our engine configuration, as the option fields are private in Template.
// TODO: Remove workaround (and the strict parameter) once we build only with golang versions with a fix.
if strict {
t.Option("missingkey=error")
} else {
t.Option("missingkey=zero")
}

// Re-inject 'include' so that it can close over our clone of t;
// this lets any 'define's inside tpl be 'include'd.
t.Funcs(template.FuncMap{
"include": includeFun(t, includedNames),
"tpl": tplFun(t, includedNames),
"tpl": tplFun(t, includedNames, strict),
})

// We need a .New template, as template text which is just blanks
Expand Down Expand Up @@ -166,7 +175,7 @@ func (e Engine) initFunMap(t *template.Template) {

// Add the template-rendering functions here so we can close over t.
funcMap["include"] = includeFun(t, includedNames)
funcMap["tpl"] = tplFun(t, includedNames)
funcMap["tpl"] = tplFun(t, includedNames, e.Strict)

// Add the `required` function here so we can use lintMode
funcMap["required"] = func(warn string, val interface{}) (interface{}, error) {
Expand Down

0 comments on commit 95905f1

Please sign in to comment.