aboutsummaryrefslogtreecommitdiff
path: root/internal/feed/template/template.go
blob: d66a8e4aadf73c7a09db37fe81dcb22dcde745a7 (plain)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package template

import (
	_ "embed"
	"errors"
	"fmt"
	html "html/template"
	"io"
	"io/fs"
	"os"
	text "text/template"

	"github.com/Necoro/feed2imap-go/pkg/log"
)

type template interface {
	Execute(wr io.Writer, data interface{}) error
	Name() string
}

type Template struct {
	template
	useHtml bool
	dflt    string
}

//go:embed html.tpl
var defaultHtmlTpl string

//go:embed text.tpl
var defaultTextTpl string

var Html = Template{
	useHtml:  true,
	dflt:     defaultHtmlTpl,
	template: html.New("Html").Funcs(funcMap),
}

var Text = Template{
	useHtml:  false,
	dflt:     defaultTextTpl,
	template: text.New("Text").Funcs(funcMap),
}

func (tpl *Template) loadDefault() {
	if err := tpl.load(tpl.dflt); err != nil {
		panic(err)
	}
}

func (tpl *Template) load(content string) (err error) {
	if tpl.useHtml {
		_, err = tpl.template.(*html.Template).Parse(content)
	} else {
		_, err = tpl.template.(*text.Template).Parse(content)
	}
	return
}

func (tpl *Template) LoadFile(file string) error {
	content, err := os.ReadFile(file)
	if err != nil {
		if errors.Is(err, fs.ErrNotExist) {
			log.Errorf("Template file '%s' does not exist, keeping default.", file)
			return nil
		} else {
			return fmt.Errorf("reading template file '%s': %w", file, err)
		}
	}

	return tpl.load(string(content))
}

func init() {
	Html.loadDefault()
	Text.loadDefault()
}