diff --git a/template/tpl.go b/template/tpl.go index 6717128..9dc3f8d 100644 --- a/template/tpl.go +++ b/template/tpl.go @@ -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 { @@ -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) }, }) @@ -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