template / files / internal / core / templating.go
templating.go
| 1 | package core |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "strings" |
| 6 | "text/template" |
| 7 | |
| 8 | "github.com/Masterminds/sprig" |
| 9 | ) |
| 10 | |
| 11 | func newTemplate() *template.Template { |
| 12 | t := template.New("text-template") |
| 13 | t = t.Option("missingkey=error") |
| 14 | t = t.Funcs(sprig.FuncMap()) |
| 15 | return t |
| 16 | } |
| 17 | |
| 18 | func parseAndExecTemplate(t *template.Template, text ParameterizedText, data any) (string, error) { |
| 19 | // parse template |
| 20 | template, err := t.Parse(string(text)) |
| 21 | if err != nil { |
| 22 | return "", fmt.Errorf("error parsing template text: %v", err) |
| 23 | } |
| 24 | |
| 25 | // create output string |
| 26 | sb := new(strings.Builder) |
| 27 | err = template.Execute(sb, data) |
| 28 | if err != nil { |
| 29 | return "", fmt.Errorf("error creating templated file: %v", err) |
| 30 | } |
| 31 | |
| 32 | templateString := sb.String() |
| 33 | return templateString, nil |
| 34 | } |