Skip to content

Commit

Permalink
update RenderTpl to only include specified .tpl files
Browse files Browse the repository at this point in the history
  • Loading branch information
seemywingz committed May 14, 2024
1 parent 1c356cd commit 370e323
Showing 1 changed file with 22 additions and 26 deletions.
48 changes: 22 additions & 26 deletions template/tpl.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,35 @@ import (
)

// include function to include other templates
func include(name string, data interface{}, tpl *template.Template) (string, error) {
func include(name string, data interface{}, tpl *template.Template, baseDir string) (string, error) {
var buf bytes.Buffer
err := tpl.ExecuteTemplate(&buf, name, data)

// Construct the file path for the included template
includePath := filepath.Join(baseDir, name)

// Read and parse the included template
includeContent, err := os.ReadFile(includePath)
if err != nil {
return "", err
}

// Parse the included template content
includeTpl, err := tpl.New(name).Parse(string(includeContent))
if err != nil {
return "", err
}

// Execute the included template
err = includeTpl.ExecuteTemplate(&buf, name, data)
if err != nil {
return "", err
}

return buf.String(), nil
}

// RenderTpl renders the given Helm .tpl template with the provided bindings and automatically includes additional templates from a directory.
func RenderTpl(filePath string, bindings map[string]interface{}) ([]byte, error) {

// Read the input template file.
input, err := os.ReadFile(filePath)
if err != nil {
Expand All @@ -30,9 +47,10 @@ func RenderTpl(filePath string, bindings map[string]interface{}) ([]byte, error)

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

Expand All @@ -42,28 +60,6 @@ func RenderTpl(filePath string, bindings map[string]interface{}) ([]byte, error)
return nil, err
}

// Load and parse all templates from the directory.
templateDir := filepath.Join(filepath.Dir(filePath))
files, err := os.ReadDir(templateDir)
if err != nil {
return nil, err
}

for _, file := range files {
if file.IsDir() {
continue
}
filePath := filepath.Join(templateDir, file.Name())
content, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
_, err = tpl.New(file.Name()).Parse(string(content))
if err != nil {
return nil, err
}
}

// Create a buffer to hold the rendered template.
var buffer bytes.Buffer

Expand Down

0 comments on commit 370e323

Please sign in to comment.