| 1 | package standard |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "os" |
| 6 | "text/template" |
| 7 | ) |
| 8 | |
| 9 | // Templater is the standard implementation of ApplyTemplate using the "text/template" library. |
| 10 | type Templater struct { |
| 11 | templates map[string]*template.Template |
| 12 | } |
| 13 | |
| 14 | // GetTemplate attempts to retrieve the template identified with id. |
| 15 | func (t *Templater) GetTemplate(id string) (*template.Template, bool) { |
| 16 | tpl, found := t.templates[id] |
| 17 | |
| 18 | return tpl, found |
| 19 | } |
| 20 | |
| 21 | // SetTemplateFile creates a new template from the file and assigns it the id. |
| 22 | func (t *Templater) SetTemplateFile(templateID, file string) error { |
| 23 | bytes, err := os.ReadFile(file) |
| 24 | if err != nil { |
| 25 | return fmt.Errorf("reading template file %q for ID %q: %w", file, templateID, err) |
| 26 | } |
| 27 | |
| 28 | return t.SetTemplateString(templateID, string(bytes)) |
| 29 | } |
| 30 | |
| 31 | // SetTemplateString creates a new template from the body and assigns it the id. |
| 32 | func (t *Templater) SetTemplateString(templateID, body string) error { |
| 33 | tpl, err := template.New("").Parse(body) |
| 34 | if err != nil { |
| 35 | return fmt.Errorf("parsing template string for ID %q: %w", templateID, err) |
| 36 | } |
| 37 | |
| 38 | if t.templates == nil { |
| 39 | t.templates = make(map[string]*template.Template, 1) |
| 40 | } |
| 41 | |
| 42 | t.templates[templateID] = tpl |
| 43 | |
| 44 | return nil |
| 45 | } |