package main import ( "os" "path/filepath" "strings" "text/template" ) func ParseTemplates(tmpl *template.Template, path string) (map[string]*template.Template, error) { tmplMap := map[string]*template.Template{} err := parseTemplates(tmpl, tmplMap, path, path) if err != nil { return nil, err } return tmplMap, nil } func parseTemplates(tmpl *template.Template, tmplMap map[string]*template.Template, path string, trimPrefix string) error { var err error dirEntries, err := os.ReadDir(path) if err != nil { return err } for _, dirEntry := range dirEntries { entryPath := filepath.Join(path, dirEntry.Name()) if dirEntry.IsDir() { err = parseTemplates(tmpl, tmplMap, entryPath, trimPrefix) if err != nil { return err } continue } data, err := ReadFileString(entryPath) if err != nil { return err } tmplName := filepath.Clean(strings.TrimPrefix(entryPath, trimPrefix)) if tmplName[0] == '/' { tmplName = tmplName[1:] } tmpl, err = tmpl.New(tmplName).Parse(string(data)) if err != nil { return err } tmplMap[tmplName] = tmpl } return nil }