Skip to content

Commit

Permalink
Kevin/eng 2022 investigate tpl values templates (#33)
Browse files Browse the repository at this point in the history
* map include function for .tpl rendering

* testing added include tpl function

* update RenderTpl to take the filePath as parameter
get the template dir from the file path
ISSUES: all templates in the file path are included in the rendered template,
        need to update to only include the explicietly mentioned file

* update RenderTpl test to pass a filepath

* update RenderTpl test remove cruft

* update RenderTpl to only include specified .tpl files

* update the include directive to do a lookup of the named template as opposed to including the template file
  • Loading branch information
seemywingz authored May 16, 2024
1 parent ce04ead commit a934832
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
31 changes: 30 additions & 1 deletion template/tpl.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,42 @@ package template

import (
"bytes"
"fmt"
"text/template"

"github.com/Masterminds/sprig/v3"
)

// include function to include other templates
func include(tpl *template.Template, name string, data interface{}) (string, error) {
// include the named template from the `define` directive in the current template
inc := tpl.Lookup(name)
if inc == nil {
return "", fmt.Errorf("template %s not found", name)
}

var buffer bytes.Buffer
err := inc.Execute(&buffer, data)
if err != nil {
return "", err
}

return buffer.String(), nil
}

// RenderTpl renders the given Helm .tpl template with the provided bindings and automatically includes additional templates from a directory.
func RenderTpl(input []byte, bindings map[string]interface{}) ([]byte, error) {
tpl, err := template.New("gotpl").Funcs(sprig.TxtFuncMap()).Parse(string(input))

tpl := template.New("gotpl")

// Create a new template and add the sprig functions and the include function.
tpl.Funcs(sprig.TxtFuncMap()).Funcs(template.FuncMap{
"include": func(name string, data interface{}) (string, error) {
return include(tpl, name, data)
},
})

tpl, err := tpl.Parse(string(input))
if err != nil {
return nil, err
}
Expand Down
1 change: 1 addition & 0 deletions test/_simple.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
a basic {{ .Template }}

0 comments on commit a934832

Please sign in to comment.