File: standard_templater.go

package info (click to toggle)
golang-github-nicholas-fedor-shoutrrr 0.10.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,432 kB
  • sloc: sh: 74; makefile: 5
file content (45 lines) | stat: -rw-r--r-- 1,265 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package standard

import (
	"fmt"
	"os"
	"text/template"
)

// Templater is the standard implementation of ApplyTemplate using the "text/template" library.
type Templater struct {
	templates map[string]*template.Template
}

// GetTemplate attempts to retrieve the template identified with id.
func (templater *Templater) GetTemplate(id string) (*template.Template, bool) {
	tpl, found := templater.templates[id]

	return tpl, found
}

// SetTemplateString creates a new template from the body and assigns it the id.
func (templater *Templater) SetTemplateString(templateID string, body string) error {
	tpl, err := template.New("").Parse(body)
	if err != nil {
		return fmt.Errorf("parsing template string for ID %q: %w", templateID, err)
	}

	if templater.templates == nil {
		templater.templates = make(map[string]*template.Template, 1)
	}

	templater.templates[templateID] = tpl

	return nil
}

// SetTemplateFile creates a new template from the file and assigns it the id.
func (templater *Templater) SetTemplateFile(templateID string, file string) error {
	bytes, err := os.ReadFile(file)
	if err != nil {
		return fmt.Errorf("reading template file %q for ID %q: %w", file, templateID, err)
	}

	return templater.SetTemplateString(templateID, string(bytes))
}